我遇到了同樣的問題。在我的情況下,問題是我將Context.User設置爲GenericPrincipal而不是RolePrincipal。因此,而不是:
this.Context.User = new GenericPrincipal(customIdentity, roles);
這個固定的對我來說:
private static bool IsValidAuthCookie(HttpCookie authCookie)
{
return authCookie != null && !String.IsNullOrEmpty(authCookie.Value);
}
UPDATE:
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"); // do this to cache the results in the cookie
}
的IsValidAuthCookie法空,空檢查升級到MVC5 .NET 4.5后角色管理器停止工作(不保存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) // check if roles loaded properly (if loads old cookie from another user for example, roles won't be loaded/cached).
{
// roles not loaded. Delete and save new
Roles.DeleteCookie();
rp.IsInRole("Visitor"); // load Roles
SaveRoleCookie(rp, filterContext);
}
}
else
{
filterContext.Principal = new RolePrincipal(customIdentity);
filterContext.Principal.IsInRole("Visitor"); // do this to cache the results in the cookie.
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和全球註冊。見here。
那麼最好的方法是做什麼?我想要角色緩存在cookie中。 – 2011-06-07 20:56:49
試試錯誤並仔細選擇使用哪種方法,我想。 – Greg 2011-06-07 21:02:01
鏈接已損壞。 – 2012-08-31 14:36:13