c# - 授权属性不适用于角色

标签 c# asp.net asp.net-mvc forms-authentication

我在让 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/

相关文章:

c# - LINQ 是提高效率的新选择

asp.net - 母版页、路径和一些 ContentPlaceHolder

asp.net - 可能的 linq 错误/问题

c# - MVC Razor View 中的 LINQ

c# - 更多验证条件

C# SignalR 异常 - 连接在收到调用结果之前开始重新连接

c# - .Net Framework 4.0 中的 ASP.NET Web 服务去了哪里?

c# - 在 Photoshop 中调整图像对比度的最佳方法是什么

asp.net-mvc - 应用逻辑(认证/授权的适当位置)

c# - 获取不同的列表值