授权属性不与工作角色 [英] Authorize attribute not working with roles

查看:116
本文介绍了授权属性不与工作角色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有在获得授权属性的麻烦与角色一起工作。这就是我饰我的控制器:

I'm having trouble in getting the Authorize attribute to work with roles. This is how I've decorated my controller:

[Authorize(Roles = "admin")]
public ActionResult Index()
{
    ...
}

这是我记录一个用户:

and this is how I log a user in:

string roles = "admin";
FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(
    1,
    username,
    DateTime.Now,
    DateTime.Now.AddMinutes(30),
    false,
    roles
);
var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(authTicket));
HttpContext.Current.Response.Cookies.Add(cookie);

不过,我还会拒绝用户访问。我在哪里去了?

But my user is still denied access. Where am I going wrong?

推荐答案

我偶然发现了你的code的一个类似的例子:最高投票的答案<一个href=\"http://stackoverflow.com/questions/1822548/mvc-how-to-store-assign-roles-of-authenticated-users\">MVC - 如何存储/分配身份验证的用户的角色

I stumbled upon a similar example of your code: the highest voted answer of MVC - How to store/assign roles of authenticated users.

该AuthorizeAttribute调用 IsInRole 存储在的IPrincipal 实例方法< A HREF =htt​​p://msdn.microsoft.com/en-us/library/system.web.httpcontext.user.aspx相对=nofollow> HttpContext.User中。默认的IPrincipal没有作用,而在此情况下IsInRole将总是返回false。这就是为什么访问你的行动被拒绝。

The AuthorizeAttribute calls the IsInRole method on the IPrincipal instance stored in HttpContext.User. By default IPrincipal has no roles, and in this case IsInRole will always return false. This is why access to your action is denied.

既然你已经存储了用户的角​​色到<一个href=\"http://msdn.microsoft.com/en-us/library/system.web.security.formsauthenticationticket.userdata.aspx\"相对=nofollow>的FormsAuthenticationTicket的财产的UserData ,必须提取的权威性cookie并成一个IPrincipal的实例,自己的角色。最高投票的答案<一个href=\"http://stackoverflow.com/questions/1822548/mvc-how-to-store-assign-roles-of-authenticated-users\">MVC - 如何存储/分配提供code,你可以直接添加到您的Global.asax.cs文件,只是这做身份验证的用户的角色。我有重复了一遍如下:

Since you have stored the user's roles into the FormsAuthenticationTicket's UserData property, you must extract the roles from the auth cookie and into a IPrincipal instance yourself. The highest voted answer of MVC - How to store/assign roles of authenticated users provides the code that you can add directly into your global.asax.cs file to do just this. I have repeated it below:

protected void Application_AuthenticateRequest(Object sender, EventArgs e)
{
    HttpCookie authCookie = Context.Request.Cookies[FormsAuthentication.FormsCookieName];
    if (authCookie != null)
    {
      FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);
      string[] roles = authTicket.UserData.Split(',');
      GenericPrincipal userPrincipal = new GenericPrincipal(new GenericIdentity(authTicket.Name), roles);
      Context.User = userPrincipal;
    }
}

这篇关于授权属性不与工作角色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆