2010-11-05 12 views
13

OK, tutaj jest mój kod, aby utworzyć plik cookie uwierzytelniania:Problem tworząc trwałe uwierzytelniania cookies: ASP.NET MVC

 // get user's role 
     List<UserType> roles = rc.rolesRepository.GetUserRoles(rc.userLoginRepository.GetUserID(userName)); 
     List<string> rolesList = (from r in roles 
           select r.ToString()).ToList(); 
     string[] rolesArr = rolesList.ToArray(); 

     // create encryption cookie 
     FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(
       1, 
       userName, 
       DateTime.Now, 
       DateTime.Now.AddDays(90), 
       createPersistentCookie, 
       String.Join(";",rolesArr) //user's roles 
       ); 

     // add cookie to response stream 
     string encryptedTicket = FormsAuthentication.Encrypt(authTicket); 

     System.Web.HttpCookie authCookie = new System.Web.HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket); 
     System.Web.HttpContext.Current.Response.Cookies.Add(authCookie); 
     //FormsAuthentication.SetAuthCookie(userName, createPersistentCookie); 

i tu jest mój kod w Global.asax ustawić role użytkowników do tożsamości użytkownika:

protected void Application_AuthenticateRequest(Object sender, EventArgs e) 
    { 
     HttpCookie authCookie = Context.Request.Cookies[FormsAuthentication.FormsCookieName]; 
     if (authCookie == null || authCookie.Value == "") 
     { 
      return; 
     } 
     FormsAuthenticationTicket authTicket = null; 
     try 
     { 
      authTicket = FormsAuthentication.Decrypt(authCookie.Value); 
      string[] roles = authTicket.UserData.Split(new char[] { ';' }); 
      if (Context.User != null) 
      { 
       Context.User = new System.Security.Principal.GenericPrincipal(Context.User.Identity, roles); 
      } 
     } 
     catch 
     { 
      return; 
     } 
    } 

Jeśli jednak "createPersistentCookie" ma wartość PRAWDA w górnym przykładzie, nie jest tworzony stały plik cookie. Jeśli odkreślę ostatnią linijkę tak:

 //System.Web.HttpContext.Current.Response.Cookies.Add(authCookie); 
     FormsAuthentication.SetAuthCookie(userName, createPersistentCookie); 

to trwałe ciasteczko jest tworzone na moim dysku twardym. ALE w kodzie Global.asax pole UserData w "authTicket" jest puste, więc nie mogę poprawnie ustawić ról!

Więc muszę użyć SetAuthCookie do utworzenia trwałego cookie, ale z jakiegoś powodu pole UserData znika z trwałego pliku cookie.

Jaka jest odpowiedź?

Odpowiedz

17

Aby utworzyć trwałe ciasteczka trzeba ustawić właściwość Expires:

if (authTicket.IsPersistent) 
{ 
    authCookie.Expires = authTicket.Expiration; 
} 
+0

Tak, to nie! Dzięki wielkie. Odrąbałem sobie włosy. Teraz mogę użyć Response.Cookies.Add zamiast SetAuthCookie i tworzony jest trwały plik cookie ORAZ dane UserData nie są wygaszone (dziwne!) – Cynthia

Powiązane problemy