如果设置了FormsAuthenticationTicket,为什么User.IsInRole(“admin”)不起作用?

时间:2012-08-16 13:39:10

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

在调试器中,如果我深入了解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);
}

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

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

1 个答案:

答案 0 :(得分:0)

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

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.
}