Obecnie próbuję implementować niektóre niestandardowe zabezpieczenia w aplikacji sieci web ASP.NET MVC2.Niestandardowe IIdentity i IPrincipal za pomocą pliku cookie FormsAuthenticationTicket w MVC2
Staram się zrobić coś naprawdę proste, jak pokazuje poniższy mojego kodu, ale z jakiegoś powodu, jeśli mogę użyć atrybutu [Authorize(Roles="Admins")]
na jednym z moich działań regulatora, sprawdź Context.User.IsInRole("Admins")
lub Page.User.IsInRole("Admins")
zawsze jest fałszywe.
Jest również dziwne, że User.Identity.Name
jest również puste.
Zobacz mój kod poniżej, używam FormularzAuthenticationTicket w pliku cookie, które następnie używam w Application_AuthenticateRequest
uchwyt zdarzenia w moim Gloabl.asax, aby ustawić Context.User z obiektu GenericPrincipal
.
Mój kod logowanie:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Login(string username, string password)
{
//this would obviously do a check against the supplied username and password
if (true)
{
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, username, DateTime.Now,
DateTime.Now.AddMinutes(15), false, "Admins|Users|Members");
string encTicket = FormsAuthentication.Encrypt(ticket);
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket);
this.Response.Cookies.Add(cookie);
string url = FormsAuthentication.GetRedirectUrl(username, false);
Response.Redirect(url);
}
return View();
}
mojego kodu Global.asax:
void MvcApplication_AuthenticateRequest(object sender, EventArgs e)
{
HttpApplication application = (HttpApplication)sender;
HttpContext context = application.Context;
var cookie = context.Request.Cookies[FormsAuthentication.FormsCookieName];
if (cookie != null)
{
// Get the authentication ticket
// and rebuild the principal & identity
FormsAuthenticationTicket authTicket =
FormsAuthentication.Decrypt(cookie.Value);
string[] roles = authTicket.UserData.Split(new Char[] { '|' });
GenericIdentity userIdentity = new GenericIdentity(authTicket.Name);
GenericPrincipal userPrincipal =
new GenericPrincipal(userIdentity, roles);
context.User = userPrincipal;
}
Raz ustawić context.User powyżej można zobaczyć w oknie zegarkowym i obiekt jest ustawiony idealnie, we właściwych rolach z poprawną nazwą itp., jednak jeśli spróbuję zablokować akcje kontrolera lub użyć Dyrektora z dowolnego miejsca w mojej witrynie, zawsze ustawiany jest na pusty ciąg bez przypisanych ról !!
Zgaduję, że robię coś naprawdę głupiego, ale jeśli ktoś mógłby to wskazać, byłbym bardzo wdzięczny.
może u proszę zamieścić swoje web.config TWORZĄCEGO ustawień, proszę? –
Mam ten sam problem – Mohsen