C# – Redirect to page after Forms Authentication Timeout

asp.netcforms-authenticationsessionsession-timeout

In my asp.net web application, I'm using asp.net forms authentication with following configuration.

<authentication mode="Forms">
    <forms name=".ASPNETAUTH" loginUrl="Login.aspx" protection="None" timeout="20" />
</authentication>

After form authentication time out, I would like to redirect to a different page. For example to 'SessionTimedOut.aspx' page.

I've found other questions on here, here is one, Forms Authentication Timeout vs Session Timeout

The answer given makes sense but the first line of code has me confused.

var cookie = Retrieve AuthenticationCookie();

if (cookie == null) return;

FormsAuthenticationTicket ticket = null;

try {
    ticket = FormsAuthentication.Decrypt(cookie.Value);
} catch (Exceptoin decryptError) {
    // Handle properly
}

if (ticket == null) return; // Not authorised

if (ticket.Expiration > DateTime.Now) {
    Response.Redirect("SessionExpiredPage.aspx"); // Or do other stuff here
}

Now there is a

FormsAuthentication.GetAuthCookie()

which takes a username and bool to persist the cookie, but this is for creating an auth cookie not getting it. So, what would the var cookie, first line of code look like.

At the moment, I am using " in web config and then when user logins in settings a session and then on every post back in a page init in my base page am checking if that session is null, if so, redirecting to a session timed out page. This is not really what I want.

May have found out how to get cookie,

HttpCookie cookie = Context.Request.Cookies[FormsAuthentication.FormsCookieName];
FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(cookie.Value);

This doesn't work because when the authentication ticket expires, the cookie goes away and the the cookie var is null. Any other way to get this working? I would still like on post back check if authentication has expired and then take appropriate action. Any thoughts from anyone????

Best Answer

The thing to remember is that even though your session times out on the server end, the client end will not process anything until it's next request. At that time it will discover that it's session has expired and attempt to restart the session. A Response.Redirect or even Server.Redirect call won't help with this.

What you need to do is to synchronize your server timeout with your client timeout, and have some client script in place to redirect the user to a "Timed Out" type page. I've written up an article with some sample code on how to do that here.

Related Topic