Tôi đã gặp vấn đề tương tự. Trong trường hợp của tôi, vấn đề là tôi đã thiết lập Context.User thành GenericPrincipal chứ không phải RolePrincipal. Vì vậy, thay vì:
this.Context.User = new GenericPrincipal(customIdentity, roles);
này cố định cho tôi:
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
}
Các IsValidAuthCookie phương pháp kiểm tra cho null và trống rỗng:
private static bool IsValidAuthCookie(HttpCookie authCookie)
{
return authCookie != null && !String.IsNullOrEmpty(authCookie.Value);
}
UPDATE: Sau khi nâng cấp lên MVC5 .NET 4.5 roleManager ngừng hoạt động (không lưu vai trò trong cookie) vì vậy phải lưu bản thân mình:
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);
}
}
Nơi mã này vào AuthenticationFilter và đăng ký nó trên toàn cầu. Xem here.
Nguồn
2013-05-25 14:02:19
Vì vậy, cách tốt nhất để làm điều này là gì? Tôi muốn các vai trò để cache trong cookie. –
Dùng thử và lỗi và cẩn thận chọn phương pháp nào để sử dụng, tôi đoán vậy. – Greg
Liên kết bị hỏng. –