【问题标题】:If FormsAuthenticationTicket is set, why doesn't User.IsInRole("admin") work?如果设置了 FormsAuthenticationTicket,为什么 User.IsInRole("admin") 不起作用?
【发布时间】:2012-08-16 21:46:36
【问题描述】:

在调试器中,如果我深入研究 User 对象,我可以看到当前成员的 UserData 属性 ((System.Web.Security.FormsIdentity)(User.Identity)).Ticket.UserData 中包含“admin”。

User.Identity.IsAuthenticated 有效,User.IsInRole("admin") 返回 false。

如果“admin”在 UserData 属性中,那么 User.IsInRole("admin") 不应该返回 true 吗?

更新

我这样设置 FormsAuthenticationTicket:

public static string CreateEncryptedTicket(string username, string roles, DateTime expireAt, bool isPersistent = true) {
    var ticket = new FormsAuthenticationTicket(1, username, DateTime.Now, expireAt, isPersistent, roles, FormsAuthentication.FormsCookiePath);
    return FormsAuthentication.Encrypt(ticket);
}

然后(其中角色是成员所在角色的逗号分隔列表):

var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, MemberService.CreateEncryptedTicket(member.Id, roles, expireDate));
HttpContext.Response.Cookies.Add(cookie);

【问题讨论】:

  • 您是否在web.config文件中使用并设置了Role Provider
  • 其实,没有……刚刚查过了。有没有办法在没有 SQL 提供程序的情况下使用 RoleManager?我在这个项目中使用 RavenDb...只是希望能够使用User.IsInRole("admin") 来检查用户是否处于管理员角色...
  • 你可以实现你自己的 RoleProvider,检查我的回答,我说一点:stackoverflow.com/a/5702000/28004 你应该使用你的自定义数据库来实现你自己的提供者......即使我使用 SQL 的大部分有时,我总是使用自己的提供商。

标签: asp.net-mvc cookies forms-authentication


【解决方案1】:

如果您这样列出用户的角色,您会看到什么?

public ActionResult ShowUserRoles() {
    string[] roles = Roles.GetRolesForUser();
    // Just hover your mouse over roles above since you're debugging...
    return View(roles); // This view probably doesn't exist.
}

【讨论】:

  • <roleManager enabled="true"></roleManager> 添加到Web.Config 后,我得到Roles | {string[0]}
猜你喜欢
  • 1970-01-01
  • 2015-11-06
  • 1970-01-01
  • 2013-03-12
  • 1970-01-01
  • 2016-09-25
  • 1970-01-01
  • 2015-09-12
  • 1970-01-01
相关资源
最近更新 更多