Ich hatte das gleiche Problem. In meinem Fall war das Problem, dass ich Context.User auf GenericPrincipal und nicht auf RolePrincipal setzte. Also statt:
this.Context.User = new GenericPrincipal(customIdentity, roles);
das für mich festgelegt:
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
}
Die IsValidAuthCookie Methode überprüft, für null und leer:
private static bool IsValidAuthCookie(HttpCookie authCookie)
{
return authCookie != null && !String.IsNullOrEmpty(authCookie.Value);
}
UPDATE: Nach dem Upgrade auf MVC5 .NET 4.5 roleManager funktioniert nicht mehr (Rollen im Cookie nicht gespeichert) und musste es selbst speichern:
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);
}
Save the 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);
}
}
Platzieren Sie diesen Code auf AuthenticationFilter und es global registrieren. Siehe here.
Also, was wäre ein besserer Weg, dies zu tun? Ich möchte, dass die Rollen im Cookie zwischengespeichert werden. –
Trial-and-Error und sorgfältig zu wählen, welche Methoden zu verwenden, denke ich. – Greg
Die Verbindung ist unterbrochen. –