Renewing forms authentication ticket - strange timing

313 views Asked by At

I'm using Forms Authentication fairly successfully, but have run into a strange issue. I've looked around the web, and haven't found the answer thus far.

I'm using some Javascript to determine when the current session is 60 seconds away from timing out, and if so - pop up a dialog box with a button which, if pressed, will extend the current FormsAuthentication ticket.

This is the code I'm using to renew the ticket. I'm simply add 5 minutes to the current expiration date of the ticket. But when I output the new expiration date, it's always under 5 minutes; normally 4 minutes and some seconds.

The code:

    string userID = HttpContext.Current.User.Identity.Name;
    HttpCookie cookie = FormsAuthentication.GetAuthCookie(userID, true);

    FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(cookie.Value);

    DateTime NEW_EXPIRY = DateTime.Now.AddMinutes(FormsAuthentication.Timeout.Minutes);

    FormsAuthenticationTicket newTicket = new FormsAuthenticationTicket(
        ticket.Version, 
        userID, 
        DateTime.Now,
        NEW_EXPIRY,
        ticket.IsPersistent,
        ticket.UserData,
        ticket.CookiePath);

    cookie.Value = FormsAuthentication.Encrypt(newTicket);

    if (ticket.IsPersistent) cookie.Expires = newTicket.Expiration;

    cookie.Secure = FormsAuthentication.RequireSSL;

    HttpContext.Current.Response.Cookies.Add(cookie);

So, here's an example output of the time differences:

The time stamp now = 16/01/2016 14:03:28 ticket expires=16/01/2016 14:07:49 (TOTAL SECONDS=261.0857244)

Why is it not resetting the expiration time to exactly 14:08:28?? I'm banging my head on the wall here...

1

There are 1 answers

0
andym0908 On

Ok so I still don't know why the expiration value from the FormsIdentity object is incorrect... so what I've done is passed the actual new expiration value (as a DateTime) back from the renewal method,and relied on that. So it seems that this value is correct, and that's the value I should be using to determine the real time out value.

Does that even make sense? I dunno, but it's working now!