授权不使用角色的属性

Jon*_*han 4 c# asp.net asp.net-mvc forms-authentication

我在使用Authorize属性来处理角色时遇到了麻烦.这就是我装饰我的控制器的方式:

[Authorize(Roles = "admin")]
public ActionResult Index()
{
    ...
}
Run Code Online (Sandbox Code Playgroud)

这就是我记录用户的方式:

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);
Run Code Online (Sandbox Code Playgroud)

但我的用户仍被拒绝访问.我哪里错了?

Adr*_*man 8

我偶然发现了一个类似的代码示例:MVC的最高投票答案- 如何存储/分配经过身份验证的用户的角色.

AuthorizeAttribute调用存储在HttpContext.User中IPrincipal实例上的IsInRole方法.默认情况下,IPrincipal没有角色,在这种情况下,IsInRole将始终返回false.这就是拒绝访问您的操作的原因.

由于您已将用户的角色存储到FormsAuthenticationTicket的UserData属性中,因此您必须自己从auth cookie中提取角色并将其提取到IPrincipal实例中.MVC的最高投票答案- 如何存储/分配经过身份验证的用户的角色提供了可以直接添加到global.asax.cs文件中的代码来执行此操作.我在下面重复一遍:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)