Tuesday, February 19, 2013

Sliding expiration explained

Sliding expiration was always a confusion to me unless I decided to dig inside the code.
This is what happening inside

Declaring Type:
System.Web.Security.FormsAuthentication
public static FormsAuthenticationTicket RenewTicketIfOld(FormsAuthenticationTicket tOld)
{
    if (tOld == null)
    {
        return null;
    }
    DateTime utcNow = DateTime.UtcNow;
    TimeSpan span = (TimeSpan) (utcNow - tOld.IssueDateUtc);
    TimeSpan span2 = (TimeSpan) (tOld.ExpirationUtc - utcNow);
    if (span2 > span) <--------So it will renew only after mid of the total timeout minutes
    {
        return tOld;
    }
    TimeSpan span3 = (TimeSpan) (tOld.ExpirationUtc - tOld.IssueDateUtc);
    DateTime expirationUtc = utcNow + span3;
    return FormsAuthenticationTicket.FromUtc(tOld.Version, tOld.Name, utcNow, expirationUtc, tOld.IsPersistent, tOld.UserData, tOld.CookiePath);
}
Above function get called by OnAuthenticate of System.Web.Security.FormsAuthenticationModule

{
…...
          if (FormsAuthentication.SlidingExpiration)
                {
                    ticket = FormsAuthentication.RenewTicketIfOld(tOld);
                }
…….
}


This implementation makes some sense because Authentication ticket's Expiration property doesn't allow it to set, so we need to create new authentication ticket.
But for me, I have to problem using slidingExpiration-
It messed up my 'about to timeout' popup (I have a SPA) at browser (although I can fix it now after understanding this logic)
It's hard to tell the QA guy that if you ideal for 16 minutes (in a timeout of 30 minutes), you will be logged-out . And all this is because ticket is not renewed when you sent your get/post at 14th minute :-(

Looks like I can’t win that battle (with QA and business) so I need to let go slidingExpiration (by setting it to false) and manually renew (recreate) the ticket for each request :-(

Wish they had allowed expiration property of FormAuthenticationTicket so that I need not to recreate the whole ticket again and again…

No comments:

Labels