MVC中的角色比较

时间:2014-01-30 13:14:56

标签: asp.net-mvc

[Authorize(Roles="ABC")]
public class HelloController : Controller
{
   //
   // GET: /Hello/
   public ActionResult Index()
   {
      return View();
   }
}

此处,具有“ABC”角色的用户可以访问Hellocontroller。 我的问题是MVC会比较角色类型“ABC”吗?

1 个答案:

答案 0 :(得分:1)

角色被添加到HttpContext的IPrincipal中。您可以创建GenericPrincipal,解析构造函数中的角色列表并将其设置为HttpContext.User。然后,可以通过User.IsInRole("role")[Authorize(Roles="role")]属性

访问GenericPrincipal

执行此操作的一种方法(在C#中)是在创建身份验证票证时将您的角色添加为用户数据参数中的逗号分隔字符串

string roles = "Admin,Member";
FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(
  1,
  userId,  //user id
  DateTime.Now,
  DateTime.Now.AddMinutes(20),  // expiry
  false,  //do not remember
  roles, 
  "/");
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName,
                                   FormsAuthentication.Encrypt(authTicket));
Response.Cookies.Add(cookie);

然后从身份验证票证访问角色列表并从Global.asax.cs创建GenericPrincipal

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(new Char[] { ',' });
      GenericPrincipal userPrincipal =
                       new GenericPrincipal(new GenericIdentity(authTicket.Name),
                                            roles);
      Context.User = userPrincipal;
    }
  }
}

来自@David Glenn的报价