FormsAuthentication does not save UserData field after Postback in .NET 3.5

I created FormsAuthenticationTicketfrom scratch, but found that when I receive it later, it UserDatadoes not return. Here is the code:

FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
                        1,
                        user.UserId,
                        DateTime.Now,
                        DateTime.MaxValue,
                        false,
                        user.UserType);

HttpCookie cookie = new HttpCookie(
     FormsAuthentication.FormsCookieName, 
     FormsAuthentication.Encrypt(ticket));

Response.Cookies.Add(cookie);

However, after reading this again on the following Request, I found that the field is UserDatanow empty:

string encryptedCookie = Request.Cookies[ FormsAuthentication.FormsCookieName ].Value;
FormsAuthenticationticket ticket = FormsAuthentication.Decrypt(encryptedCookie);
Assert.IsTrue( ticket.UserData.Length == 0 ); //TRUE!

Any ideas?

+2
source share
3 answers

I think I found the problem. If you make up your own cookie name, that seems wonderful! So change:

HttpCookie cookie = new HttpCookie(
     FormsAuthentication.FormsCookieName, 
     FormsAuthentication.Encrypt(ticket));

to

HttpCookie cookie = new HttpCookie(
     "SiteCookie", 
     FormsAuthentication.Encrypt(ticket));

And then remove it according to the question:

string encryptedCookie = Request.Cookies[ "SiteCookie" ].Value;
FormsAuthenticationticket ticket = FormsAuthentication.Decrypt(encryptedCookie);
Assert.IsFalse( ticket.UserData.Length == 0 ); //Hooray! It works

Its possible .NET does some complicated things with it, so putting it in a new one works great.

UPDATE:

, , , -:

FormsAuthentication.RenewTicketIfOld(ticket); // Do before saving cookie
+9

:

//Create Form Authentication ticket
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, currentUser.userid.ToString(), DateTime.Now, DateTime.Now.AddMinutes(60), false, currentUser.ToString(), FormsAuthentication.FormsCookiePath);

string hashCookies = FormsAuthentication.Encrypt(ticket);
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hashCookies);
cookie.HttpOnly = true;
HttpContext.Current.Response.Cookies.Add(cookie);
+1

. , , cookie, , UserData.

cookie Fiddler, , : enter image description here

, ? Login . Authenticate cookie UserData manaully. AuthenticateEventArgs.Authenticated=true, , , , cookie , FormsAuthentication.FormsCookieName! , AuthenticateEventArgs.Authenticated = true.

So, you can debug your code to check if the authentication cookie is set twice in response.

+1
source

Source: https://habr.com/ru/post/1696801/


All Articles