asp.netcookiesforms-authenticationhttpmoduleformsauthenticationticket

Re-Initialize context.User after FormsAuthenticationTicket timeout


In our application we have implemented role-based forms authentication. This has been handled using a RoleModule, where we save the Role data in cookie, and each time we read the data from the cookie and instantiate the IPrincipal object. This code is executed in Application_OnPostAcquireRequestState method:

 HttpApplication application = source as HttpApplication;
 HttpContext context = application.Context;

if (context.User.Identity.IsAuthenticated &&
      (!Roles.CookieRequireSSL || context.Request.IsSecureConnection))
{
//Read the roles data from the Roles cookie..

context.User = new CustomPrincipal(context.User.Identity, cookieValue);
Thread.CurrentPrincipal = context.User;
}

This initializes the context.User object. Each time a request is made to the server, the user is authenticated using the above flow. In the Application_EndRequest, we update the Roles cookie with the current principal object data.

There is FormsAuthentication_OnAuthenticate method in our Global.asax page, in which we read the cookie, update the cookie, and renew the ticket if it is expired. Also, in this method, we try to set the username value in the session object if the ticket is expired.

FormsAuthentication oldTicket = FormsAuthentication.Decrypt(context.Request.Cookies[FormsAuthentication.FormsCookieName].Value);
if(oldTicket != null)
{
    if(oldTicket.Expired)
    {
        try
        {
            HttpContext.Current.Session["UserName"] = userName;
        }
        catch
        {
            //Log error.
        }

    FormsAuthentication newTicket =  new FormsAuthenticationTicket(oldTicket.Version, oldTicket.Name, DateTime.Now,
            DateTime.Now.AddMinutes(30), oldTicket.IsPersistent, oldTicket.UserData);

    string encryptedTicket = FormsAuthentication.Encrypt(newTicket);
    HttpCookie httpCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
    if (isPersistent)
    {
        httpCookie.Expires = DateTime.Now.AddMinutes(300);
    }
}

Here is our forms setting in web.config:

   <forms defaultUrl="Default.aspx" domain="" loginUrl="Login.aspx" name=".ASPXFORMSAUTH" timeout="20" slidingExpiration="true" />

The session timeout is 20 mins.

The issue: If a user is idle for more than 30 mins.(which is the FormsAuth ticket renewal time duration), the context.User.Identity.IsAuthenticated value in the role module is false, and context.User is set as NULL. Now when a user requests a page he is redirected to the login page. However, the cookie is still there. If again, the user tries to request a page, the context.User.IsAuthenticated property is set to true and the user is taken to the respective page. Also, in FormsAuthentication_OnAuthenticate method, when I try to set the session value it throws an error as the session object is NULL.

What I want to achieve here is that in case of persistent cookie, after the auth ticket times out, the user should not be logged out, i.e. the user should be re-authenticated.

How can I achieve this? If I am not wrong, setting context.User should solve the purpose, but how do I go about it?

Additional Info:

After the ticket expires and i try to request a page, the event viewer shows an error message:

Event code: 4005 
Event message: Forms authentication failed for the request. Reason: The ticket supplied has expired. 
Event time: 08-02-2012 20:02:05 
Event time (UTC): 08-02-2012 14:32:05 
Event ID: 048e3238ade94fd6a7289bac36d130ef 
Event sequence: 76 
Event occurrence: 2 
Event detail code: 50202 

Process information: 
Process ID: 21692 
Process name: w3wp.exe 
Account name: IIS APPPOOL\ASP.NET v4.0 Classic 

I am using standard machine key settings, stored in web.config and not an auto-generated one. Also, I checked the process ID and its the same for all the errors.


Solution

  • I finally resolved the issue. What was happening was that when the FormsAuthentication ticket timed out, FormsAuthentication_OnAuthenticate was not able to set the context.User object, as specified in the MSDN documentation for Authenticate event:

    If you do not specify a value for the User property during the FormsAuthentication_OnAuthenticate event, the identity supplied by the forms authentication ticket in the cookie or URL is used.

    The reason for that is that I am not setting ticket.Name with the username of the user. It is an empty string. Hence it might be the case that Authenticate event was not able to get the identity of the user and create the FormsIdentity instance. As a solution, when I am renewing the expired ticket, I am also creating a GenericIdentity object and then using it to set context.User.

    IIdentity identity = new GenericIdentity(username, "Forms");
    context.User = new CustomPrincipal(identity);