I'm using FormsAuthentication, and am having trouble extending the expiry

638 Views Asked by At

I'm building a web app (framework 4.6), and am using FormsAuthentication to manage the security.

Currently, it allows the user to log in/log out etc... and all is fine. However, I want to periodically check the expiry of the Forms Authentication Ticket, and pop up a dialog box with a button that the user will press to extend the time. So I basically have it working, except that when the ticket is renewed, the user is essentially kicked out, and I have no idea why.

Here's the logging in code:

FormsAuthenticationTicket faTicket = new FormsAuthenticationTicket(1, user.UserID, DateTime.Now, DateTime.Now.AddMinutes(FormsAuthentication.Timeout.Minutes), persistLogin, "");
string cookiestr = FormsAuthentication.Encrypt(faTicket);
HttpCookie ck = new HttpCookie(FormsAuthentication.FormsCookieName, cookiestr);
if (persistLogin)
    ck.Expires = faTicket.Expiration;
ck.Path = FormsAuthentication.FormsCookiePath;
HttpContext.Current.Response.Cookies.Add(ck);

and here's the ticket renew code:

FormsIdentity identity = ((FormsIdentity)HttpContext.Current.User.Identity);
string userID = identity.Name;
HttpCookie cookie = FormsAuthentication.GetAuthCookie(userID, true);
FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(cookie.Value);

FormsAuthenticationTicket newTicket = new FormsAuthenticationTicket(
    ticket.Version,
    userID,
    ticket.IssueDate, 
    DateTime.Now.AddMinutes(FormsAuthentication.Timeout.Minutes), 
    ticket.IsPersistent, 
    ticket.UserData, 
    ticket.CookiePath);

cookie.Value = FormsAuthentication.Encrypt(newTicket);
if (ticket.IsPersistent)
    cookie.Expires = newTicket.Expiration;
HttpContext.Current.Response.Cookies.Add(cookie);

Incidentally, the way I'm working on the time remaining is as follows (within a ashx handler file):

FormsIdentity identity = ((FormsIdentity)HttpContext.Current.User.Identity);
DateTime expires = identity.Ticket.Expiration;

// offset the expiry time by a few seconds, because otherwise the FormsAuthentication will prevent this Handler from executing
expires = expires.AddSeconds(-5);

TimeSpan ts = expires - DateTime.Now;
double mins = ts.Minutes;
double secs = ts.Seconds;
string countdownText = mins.ToString().PadLeft(2, '0') + ":" + secs.ToString().PadLeft(2, '0');
1

There are 1 best solutions below

5
Ross Bush On

Since you are reissuing the ticket, it might make sense to set the issued date to the current date -->

FormsAuthenticationTicket newTicket = new FormsAuthenticationTicket(
    ticket.Version,
    userID,
    DateTime.Now,//ticket.IssueDate 
    DateTime.Now.AddMinutes(FormsAuthentication.Timeout.Minutes), 
    ticket.IsPersistent, 
    ticket.UserData, 
    ticket.CookiePath);