How to log out a user when a session times out or ends
Asked Answered
A

2

12

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

Thanks for any help.

Amid answered 10/12, 2010 at 22:31 Comment(2)
Do you mean simply to have a user become non-authenticated, or to actually redirect the user to some "Hey, you've timed out!" page after they've waited too long and their session has expired?Testes
when the session ends, the next request they make will be non-authenticated. In which case your page can check for that on loading a new page. To redirect them if they have been on the same page too long, you'll want to write javascript to the page that has a count down timer that equals the session timeout value. When the timer hits zero redirect, becuase the session is invalid. (Kinda - one caveat is that if they are browsing your site in another tab - that will keep the session alive, while the first tab javascript will still count down)Supernational
T
12

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 !

Testes answered 11/12, 2010 at 0:8 Comment(0)
S
1

If you are using the .net Membership Provider, just set the Timeout-setting in the web.config http://msdn.microsoft.com/en-us/library/h6bb9cz9(v=VS.100).aspx

Sporogenesis answered 10/12, 2010 at 22:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.