NeilC
NeilC

Reputation: 1390

Determine when an ASP.NET Forms Authentication will expire

Is it possible to determine the date & time when an ASP.NET session will expire when using Forms Authentication?

I would like to warn users when their sessions are about to expire. There is no session state & sliding expiration is disabled. Here are some of the system.web settings:

<authentication mode="Forms">
  <forms defaultUrl="Default.aspx" loginUrl="Login.aspx" requireSSL="false" enableCrossAppRedirects="true" cookieless="AutoDetect" timeout="2" slidingExpiration="false"/>
</authentication>

<sessionState mode="Off"/>

The timeout / lifetime of a session is easy to determine, but should the user refresh the page within the session windows, adding the lifetime value to the date-time at reload will not be accurate.

Using an authentication cookie with FormsAuthenticationTicket ticket encrypted as its value, one can decrypt it to get the expiration date-time.

Although some AJAX calls may be made, the user might interact with the UI without any post back or request to the webserver.

Any ideas on how I can achieve this type of behavior without the use of cookies?

Upvotes: 2

Views: 1797

Answers (1)

danyo
danyo

Reputation: 39

I have a similar problem. In my case given the low number of users, im opting for a better user experience with a polling ajax call on the page to call back into the server and check the expiration ticket. You may be able to get away with tweaking the below code and including expiration info in the page via http and keeping track of time in client javascript if you dont want to go the ajax route.

        if (User.Identity.IsAuthenticated)
        {
            var identity = (FormsIdentity)User.Identity;    
            viewModel.UtcInactivityExpiryDate = identity.Ticket.Expiration.ToUniversalTime();                
        }

If you go the ajax route, there is another gotcha. You have to stop the ajax call itself from renewing the inactivity timeout if you are using one. You can do that by overwriting the new authentication cookie with the original one. at the end of your ajax request.

            var requestCookie = HttpContext.Current.Request.Cookies[".ASPXAUTH"];
            if (requestCookie != null)
            {
                HttpContext.Current.Response.Cookies.Add(requestCookie);
            }

Upvotes: 3

Related Questions