views:

13

answers:

1

I've created a FormsAuthenticationTicket from scratch, but found that when retrieving it at a later time, the UserData isn't coming back. Here is the code used:

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, when reading this back on the next Request, I found that the UserData field is now empty:

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

Any ideas?

A: 

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
Dominic Zukiewicz