How to Handle Forms Authentication Timeout Exceptions in ASP.NET

Forms Authentication Timeout Logging

Session and forms authentication have two completely separate timeouts.
See my posting on this here:

How can I handle forms authentication timeout exceptions in ASP.NET?

In Application_PreRequestHandlerExecute you need to check the ticket.

Also be sure your session and forms auth timeouts are in sync using the code I posted there. Not just setting both to say 60 minutes. Since forms auth doesn't update the 'touched' time until half of the time passes by, and session time is updated on every request, they get out of sync.

Handling Forms Authentication timeout in ASP.net

No you can not because the timeout is encoded on the authentication cookie, and is lives on the browser (not on server side).

You can either make that custom, to also keep on a database the user timeout - but its not so easy, and alternative you can use the Application_AuthenticateRequest on global.asax to check right before the request if the user is not authenticated any more.

One example on how to remove session data if the the user is not authenticate. On global asax.

protected void Application_AuthenticateRequest(Object sender, EventArgs e)
{
// get the authCookie
HttpCookie authCookie = Context.Request.Cookies[cookieName];
// if is null then the use is not Authendicated
if (null == authCookie && System.Web.HttpContext.Current.Session != null)
{
// now check if you have Session variables that you wish to remove.
if(System.Web.HttpContext.Current.Session["flag"] == "1")
{
// remove your session data

}
}
}

You maybe also check with

if(HttpContext.Current.User == null || HttpContext.Current.User.Identity == null || !HttpContext.Current.User.Identity.IsAuthenticated)
{
// now check if you have Session variables that you wish to remove.
if(Session["flag"] == "1")
{
// remove your session data

}
}

Forms Authentication Timeout vs Session Timeout

  1. To be on the safe side: TimeOut(Session) <= TimeOut(FormsAuthentication) * 2
  2. If you want to show page other than specified in loginUrl attribute after authentication timeout you need to handle this manually as ASP.NET does not provide a way of doing it.

To achieve #2 you can manually check the cookie and its AuthenticationTicket for expiration and redirect to your custom page if they have expired.

You can do in it in one of the events: AcquireRequestState, AuthenticateRequest.

Sample code in the event can look like:

// Retrieve AuthenticationCookie
var cookie = Request.Cookies[FormsAuthentication.FormsCookieName];
if (cookie == null) return;
FormsAuthenticationTicket ticket = null;
try {
ticket = FormsAuthentication.Decrypt(cookie.Value);
} catch (Exception decryptError) {
// Handle properly
}
if (ticket == null) return; // Not authorised
if (ticket.Expiration > DateTime.Now) {
Response.Redirect("SessionExpiredPage.aspx"); // Or do other stuff here
}

Forms Authentication Timeout Being Ignored

I found the cause of all my problems. I found a bunch of code in global.asax that manipulates the user's session and essentially overrides forms authentication. This code runs on every request to the server and keeps the user logged in as long as they are still authenticated in the session. This means that even if the forms auth cookie expired(which it did!) the user would remain logged in. I'm guessing the previous developers started out with forms auth and then decided to write their own thing for some reason. We decided to change the session timeout so that users would be logged out after 5 minutes instead of the default 20.

Here is some of the code from global.asax that is responsible for me almost going bald:

 protected void Application_PreRequestHandlerExecute()
{
HttpSessionState session = HttpContext.Current.Session;
if (session == null)
return;

IUser user = (session[HttpSecurityContext.SECURITY_CONTEXT_KEY] as IUser) ?? CreateUser();
securityContext.SetCurrent(user);
}

protected void Application_PostRequestHandlerExecute()
{
HttpSessionState session = HttpContext.Current.Session;
if (session == null) return;

session[HttpSecurityContext.SECURITY_CONTEXT_KEY] = securityContext.Current;
}

private IUser CreateUser()
{
IUserLocation location = LocateUser();
IUser user = Common.Security.User.CreateAnonymous(location);
SetupUserPreferences(user);
return user;
}

And this is what we changed in web.config for the session timeout:

<system.web>
<sessionState timeout="5"/>
</system.web>

Forms authentication timeout vs sessionState timeout

They are different things. The Forms Authentication Timeout value sets the amount of time in minutes that the authentication cookie is set to be valid, meaning, that after value number of minutes, the cookie will expire and the user will no longer be authenticated—they will be redirected to the login page automatically. The slidingExpiration=true value is basically saying that as long as the user makes a request within the timeout value, they will continue to be authenticated (more details here). If you set slidingExpiration=false the authentication cookie will expire after value number of minutes regardless of whether the user makes a request within the timeout value or not.

The SessionState timeout value sets the amount of time in minutes a Session State provider is required to hold data in memory (or whatever backing store is being used, SQL Server, OutOfProc, etc) for a particular session. For example, if you put an object in Session using the value in your example, this data will be removed after 30 minutes. The user may still be authenticated but the data in the Session may no longer be present. The Session Timeout value is always reset after every request as suggested here and here (might require cookies; vs cookieless)

Forms Authentication timing out when it shouldn't?

This may also happen when iis recycles or terminates the application pool.

You may want to check Troubleshoot Forms Authentication It could be that the client lost their cookie.

If you manually generate the authentication ticket, you need to set the timeout in code and not the web.config

What is unit of Forms Authentication timeout in Asp.net?

<forms loginUrl="~/Account/Login" timeout="2880" />

FormAuthentication timeout is in minutes. 2880 means 48 hours.

Default is 30 minutes if you do not explicitly set it.



Related Topics



Leave a reply



Submit