我是同样遇到了这个问题。在我的情况下,问题是我将 Context.User 设置为 GenericPrincipal 而不是 RolePrincipal。所以应该改成:
this.Context.User = new GenericPrincipal(customIdentity, roles)
这对我有用:
HttpCookie roleCookie = this.Context.Request.Cookies[Roles.CookieName];
if (IsValidAuthCookie(roleCookie))
{
this.Context.User = new RolePrincipal(customIdentity, roleCookie.Value);
}
else
{
this.Context.User = new RolePrincipal(customIdentity);
var x = this.Context.User.IsInRole("Visitor");
}
IsValidAuthCookie 方法检查是否为 null 或空:
private static bool IsValidAuthCookie(HttpCookie authCookie)
{
return authCookie != null && !String.IsNullOrEmpty(authCookie.Value);
}
更新:升级到MVC5 .NET 4.5后,roleManager停止工作(不保存cookie中的角色),因此我不得不自己保存它:
HttpCookie roleCookie = filterContext.HttpContext.Request.Cookies[Roles.CookieName];
if (IsValidAuthCookie(roleCookie))
{
filterContext.Principal = new RolePrincipal(customIdentity, roleCookie.Value);
RolePrincipal rp = (RolePrincipal)filterContext.Principal;
if (!rp.IsRoleListCached)
{
Roles.DeleteCookie();
rp.IsInRole("Visitor");
SaveRoleCookie(rp, filterContext);
}
}
else
{
filterContext.Principal = new RolePrincipal(customIdentity);
filterContext.Principal.IsInRole("Visitor");
SaveRoleCookie(filterContext.Principal as RolePrincipal, filterContext);
}
保存 roleCookie
private void SaveRoleCookie(RolePrincipal rp, AuthenticationContext filterContext)
{
string s = rp.ToEncryptedTicket();
const int MAX_COOKIE_LENGTH = 4096;
if (string.IsNullOrEmpty(s) || s.Length > MAX_COOKIE_LENGTH)
{
Roles.DeleteCookie();
}
else
{
HttpCookie cookie = new HttpCookie(Roles.CookieName, s);
cookie.HttpOnly = true;
cookie.Path = Roles.CookiePath;
cookie.Domain = Roles.Domain;
if (Roles.CreatePersistentCookie)
cookie.Expires = rp.ExpireDate;
cookie.Secure = Roles.CookieRequireSSL;
filterContext.HttpContext.Response.Cookies.Add(cookie);
}
}
将此代码放在AuthenticationFilter上并全局注册。请参见
这里。