मुझे एक ही समस्या थी। मेरे मामले में मुद्दा यह था कि मैं Context.User जेनेरिक प्रिंसिपल को स्थापित कर रहा था और रोल प्रिंसिपल नहीं। तो बजाय:
this.Context.User = new GenericPrincipal(customIdentity, roles);
यह मेरे लिए तय:
private static bool IsValidAuthCookie(HttpCookie authCookie)
{
return authCookie != null && !String.IsNullOrEmpty(authCookie.Value);
}
अद्यतन:
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 पर अपग्रेड करने के बाद भूमिका प्रबंधक ने काम करना बंद कर दिया (कुकी में भूमिकाओं को सहेज नहीं रहा) इसलिए इसे खुद को सहेजना पड़ा:
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 देखें।
स्रोत
2013-05-25 14:02:19
तो ऐसा करने का बेहतर तरीका क्या होगा? मैं कुकी में पकाने की भूमिका चाहता हूं। –
परीक्षण-और-त्रुटि और सावधानी से चयन करना कि कौन सी विधियों का उपयोग करना है, मुझे लगता है। – Greg
लिंक टूटा हुआ है। –