FormsAuthentication isn't preserving the UserData field after Postback in .NET 3.5

∥☆過路亽.° 提交于 2019-12-03 20:34:25

I think I found the problem. If you make up your own cookie name it seems to be fine! So change from:

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

to

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

And then retrieve it as per 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 tricky stuff with it, so by putting it in a new one works fine.

UPDATE:

Also, the ticket needs to be refreshed, as otherwise the ticket will expire while the user is using the website:

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

This works for me:

//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);

I have also encountered this problem. But I think the real reason is that the server set the same cookie twice and the second override the first which contains your UserData field.

You can capture the cookie writing process by Fiddler, and here is a screenshot that show this problem:

So, how this happened? In my situation, I use the Login control to authenticate. In the Login control's Authenticate event, I set the cookie with my UserData after check the username and password manaully. Then, I set the AuthenticateEventArgs.Authenticated=true, at this time, in the debug window, I see a new cookie is queued to the response which name is also equal to FormsAuthentication.FormsCookieName ! My solution is redirect to the Default page instead of setting the AuthenticateEventArgs.Authenticated=true.

So, you may debug your code to see if the authentication cookie is queued to the response twice.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!