MVC 3 身份验证/授权:缺少角色

发布于 2024-12-19 19:35:41 字数 506 浏览 2 评论 0原文

我们使用 MVC 3。默认的用户管理对我们来说不可用,因为我们的帐户信息存储在我们自己的数据存储中,并且访问通过我们自己的存储库类进行。

我正在尝试为 HttpContext.User 分配一个主体添加角色并给出一个授权 cookie。

根据截取的代码,我发现我尝试了这样的操作:

if (UserIsOk(name, password))
{
    HttpContext.User =
        new GenericPrincipal(
            new GenericIdentity(name, "Forms"),
            new string[] { "Admin" }
        );
    FormsAuthentication.SetAuthCookie(name, false);

    return Redirect(returnUrl);
}

当下一个请求完成时,用户已通过身份验证,但他不处于“管理员”角色。 我缺少什么?

We use MVC 3. The default user management is not usable for us as our account info is stored in our own data-store and access goes via our own repository classes.

I'm trying to assign a principal add roles to the HttpContext.User and give out an authorization cookie.

Based on a code snipped I found I tried something like this:

if (UserIsOk(name, password))
{
    HttpContext.User =
        new GenericPrincipal(
            new GenericIdentity(name, "Forms"),
            new string[] { "Admin" }
        );
    FormsAuthentication.SetAuthCookie(name, false);

    return Redirect(returnUrl);
}

When the next request is done, the user is authenticated, but he is not in the "Admin" role.
What am I missing?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

逆光飞翔i 2024-12-26 19:35:41

我认为你应该实施FormsAuthenticationTicket
更多信息请参见:http://msdn.microsoft。 com/en-us/library/aa289844(v=vs.71).aspx

在Mvc中它非常相似。

我有一个名为 UserSession 的类,它被注入到 LoginController 中,并在 LogOn 操作中使用:

    [HttpPost, ValidateAntiForgeryToken]
public ActionResult Index(LoginInput loginInput, string returnUrl)
{
    if (ModelState.IsValid)
    {
        return (ActionResult)_userSession.LogIn(userToLog, loginInput.RememberMe, CheckForLocalUrl(returnUrl), "~/Home");
    }
}

这是我的 UserSession LogIn 实现(请注意,我为示例硬编码了“Admin”角色,但您可以将其作为参数传递):

public object LogIn(User user, bool isPersistent, string returnUrl, string redirectDefault)
    {
        var authTicket = new FormsAuthenticationTicket(1, user.Username, DateTime.Now, DateTime.Now.AddYears(1), isPersistent, "Admin", FormsAuthentication.FormsCookiePath);
        string hash = FormsAuthentication.Encrypt(authTicket);

        var authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, hash);

        if (authTicket.IsPersistent) authCookie.Expires = authTicket.Expiration;

        HttpContext.Current.Response.Cookies.Add(authCookie);

        if (!String.IsNullOrEmpty(returnUrl))
            return new RedirectResult(HttpContext.Current.Server.UrlDecode(returnUrl));

        return new RedirectResult(redirectDefault);
    }

然后我已经重写了基本控制器 OnAuthorization 方法来获取 cookie:

if (filterContext.HttpContext.Current.User != null)
{
   if (filterContext.HttpContext.Current.User.Identity.IsAuthenticated)
   {
      if( filterContext.HttpContext.Current.User.Identity is FormsIdentity ) 
      {
         FormsIdentity id = filterContext.HttpContext.Current.User.Identity as FormsIdentity;
         FormsAuthenticationTicket ticket = id.Ticket;
         string roles = ticket.UserData;

         filterContext.HttpContext.Current.User = new GenericPrincipal(id, roles);
      }
   }
}

我希望这会有所帮助。让我知道。

I think you should implement FormsAuthenticationTicket.
More info here : http://msdn.microsoft.com/en-us/library/aa289844(v=vs.71).aspx

In Mvc it is quite similar.

I have a class called UserSession that is injected into LoginController and that I use in LogOn action :

    [HttpPost, ValidateAntiForgeryToken]
public ActionResult Index(LoginInput loginInput, string returnUrl)
{
    if (ModelState.IsValid)
    {
        return (ActionResult)_userSession.LogIn(userToLog, loginInput.RememberMe, CheckForLocalUrl(returnUrl), "~/Home");
    }
}

Here's my UserSession LogIn implementation (notice I put the "Admin" role hard coded for the example, but you could pass it as argument) :

public object LogIn(User user, bool isPersistent, string returnUrl, string redirectDefault)
    {
        var authTicket = new FormsAuthenticationTicket(1, user.Username, DateTime.Now, DateTime.Now.AddYears(1), isPersistent, "Admin", FormsAuthentication.FormsCookiePath);
        string hash = FormsAuthentication.Encrypt(authTicket);

        var authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, hash);

        if (authTicket.IsPersistent) authCookie.Expires = authTicket.Expiration;

        HttpContext.Current.Response.Cookies.Add(authCookie);

        if (!String.IsNullOrEmpty(returnUrl))
            return new RedirectResult(HttpContext.Current.Server.UrlDecode(returnUrl));

        return new RedirectResult(redirectDefault);
    }

Then in the base controller I've overriden OnAuthorization method to get the cookie :

if (filterContext.HttpContext.Current.User != null)
{
   if (filterContext.HttpContext.Current.User.Identity.IsAuthenticated)
   {
      if( filterContext.HttpContext.Current.User.Identity is FormsIdentity ) 
      {
         FormsIdentity id = filterContext.HttpContext.Current.User.Identity as FormsIdentity;
         FormsAuthenticationTicket ticket = id.Ticket;
         string roles = ticket.UserData;

         filterContext.HttpContext.Current.User = new GenericPrincipal(id, roles);
      }
   }
}

I hope this helps. Let me know.

一百个冬季 2024-12-26 19:35:41

您确定该角色已启用,并且有这样的角色吗?

如果没有,请执行以下操作:
在视觉工作室中:
项目-> ASP.NET 配置

然后选择安全性,启用角色。创建角色“管理员”。

然后尝试你的方法

You sure, that roles are enabled, and there is such role?

If not, do following:
In Visual Studio:
Project -> ASP.NET Configuration

Then choose Security, enable roles. Create role "Admin".

Then try your approach

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文