我在让 Authorize
属性与角色一起使用时遇到问题。这就是我装饰 Controller 的方式:
[Authorize(Roles = "admin")]
public ActionResult Index()
{
...
}
这就是我登录用户的方式:
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);
但我的用户仍然被拒绝访问。我哪里错了?
最佳答案
我偶然发现了一个类似的代码示例:MVC - How to store/assign roles of authenticated users 的最高投票答案.
AuthorizeAttribute 调用 IsInRole IPrincipal 上的方法存储在 HttpContext.User 中的实例.默认情况下 IPrincipal 没有角色,在这种情况下 IsInRole 将始终返回 false。这就是拒绝访问您的操作的原因。
由于您已将用户的角色存储到 FormsAuthenticationTicket's UserData property 中,您必须自己从 auth cookie 中提取角色并将其放入 IPrincipal 实例中。 MVC - How to store/assign roles of authenticated users 的最高投票答案提供可以直接添加到 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;
}
}
关于c# - 授权属性不适用于角色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18807806/