角色已添加到知识产权校长HttpContext 的。您可以创建一个通用主体,在构造函数中解析角色列表并将其设置为 HttpContext.User。然后可以通过以下方式访问 GenericPrincipalUser.IsInRole("role")
or the [Authorize(Roles="role")]
属性
执行此操作的一种方法(在 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;
}
}