I have been playing around with putting forms based authentication on a site I am building. I would like to store a piece of information in the authentication ticket and persist that cookie on the client between sessions. So naturally, I searched around the net and kept coming across some code that looks something like this:
if (FormsAuthentication.Authenticate(UsernameTextBox.Text, PasswordTextBox.Value))
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
string encryptedTicket = FormsAuthentication.Encrypt(ticket);
HttpCookie authenticationCookie = new HttpCookie(FormsAuthentication.FormsCookieName,encryptedTicket);
The only problem is that the authentication ticket doesn’t stick around between sessions even though I pass true to the isPersistent parameter of the FormsAuthenticationTicket constructor. Each time I start a new browser up, I find that I am no longer authenticated. So what’s the problem?
If you don’t specify the cookie’s expiration date, it expires when you close the browser, right? The solution is to add the following line before adding the cookie to the Response.Cookies collection:
authenticationCookie.Expires = ticket.Expiration;