Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to log out a user when a session times out or ends

Whats the best way to log out a user when a session ends or expires?

Thanks for any help.

like image 970
zSynopsis Avatar asked Dec 10 '10 22:12

zSynopsis


1 Answers

It really depends on the desired functionality you're looking for. I'm going to assume you're using FormsAuthentication.

There's two separate things you need to be concerned about: the Session and the FormsAuthentication cookie. Unless I'm mistaken, both of these have separate timeouts.

If the problem you're having is that the session is timed out but the user still is authenticated, you could try a combination of the following:

1: Making sure the authentication cookie has the same timeout value as the session:

<authentication mode="Forms"><forms ... timeout="20" ... ><authentication>
<sessionState ... timeout="20" ... />

2: In your Page_Load event, check if the session has timed out:

if (context.Session != null && Context.Session.IsNewSession == true &&
    Page.Request.Headers["Cookie"] != null &&
    Page.Request.Headers["Cookie"].IndexOf("ASP.NET_SessionId") >= 0)
{
    // session has timed out, log out the user
    if (Page.Request.IsAuthenticated)
    {
        FormsAuthentication.SignOut();
    }
    // redirect to timeout page
    Page.Response.Redirect("/Timeout.aspx");
}

(See http://www.eggheadcafe.com/articles/20051228.asp for information on detecting a session timeout)

If you want a more pleasant user experience, you could use javascript to initiate some sort of a modal UI popup after X minutes. This popup would simply allow a user to initiate a button-click which would trigger an AJAX postback on the server, thus extending their authentication and session cookie without them having to reload the page. I've never implemented this before but look, this guy made an ASP.NET AJAX control !

like image 119
Pandincus Avatar answered Oct 05 '22 22:10

Pandincus