Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the purpose of FormsAuthenticationTicket isPersistent property?

Tags:

I'm trying to get my head round the purpose of the isPersistent property found on the FormsAuthenticationTicket class. http://msdn.microsoft.com/en-us/library/kybcs83h.aspx

  1. Are there scenarios when setting isPersistent works?
  2. In what scenarios would I want to set isPersistent to true and false?

The property seems to be redundant since I've found the only way for me to persist my users authentication cookie across browser sessions is to set the Expires property of the cookie created following ticket creation; even if the tickets isPersistent value is set to false.

I also found that setting the tickets expiry (not the cookie) to something like 10 seconds with isPersistent set to true has little effect; the ticket expires after 10 seconds.

FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1,
    identity.Name,
    DateTime.Now,
    DateTime.Now.AddMinutes(FormsAuthentication.Timeout.TotalMinutes),
    isPersistent,
    JsonSerializerService.ToJson(identity),
    FormsAuthentication.FormsCookiePath);

string encryptedTicket = FormsAuthentication.Encrypt(ticket);

var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);

cookie.Path = FormsAuthentication.FormsCookiePath;

cookie.Expires = DateTime.Now.AddYears(1); // good for one year

I appreciate that I can change my above code to optionally set expires

if (isPersistent)
    cookie.Expires = DateTime.Now.AddYears(1); // good for one year

An example application has been created @ GitHub. https://github.com/chrismoutray/AuthSample This basically shows that even by setting the isPersistent flag to true the cross browser authorization doesn't work.

like image 445
Chris Moutray Avatar asked Apr 27 '12 06:04

Chris Moutray


1 Answers

In framework 1.0/1.1, setting IsPersistent to true would set an expiration of 50 years to the cookie.
In version 2.0 it was changed so the expiration of the cookie matches the form authentication timeout attribute. So you can set IsPersistent to true but the cookie will always expire after the form authentication timeout period.
Your code does the trick if you want long expiration period without modifying forms authentication timeout.

edit: I've downloaded your sample and replaced your cookie code with

 FormsAuthentication.SetAuthCookie(model.UserName, true);

And it's working as expected: with two days configured as your form timeout, my cookie will expire in two days.

like image 125
lnu Avatar answered Sep 21 '22 14:09

lnu