Search code examples
asp.netsecuritysessionforms-authentication

How to synchronize lifetime of forms authentication cookie and Asp.Net Session?


I am building an ASP.NET web site that uses FormsAuthentication and a standard Session mechanism with configuration like:

<authentication mode="Forms">
    <forms cookieless="UseCookies" name=".MyAppAuth" loginUrl="~\Login.aspx" timeout="20"/>
</authentication>
...
<sessionState timeout="20" cookieless="UseCookies" />

It seems that the lifetime of an authentication cookie is not equal to the lifetime of the user Session. So ASP.NET doesn't guarantee that

  1. Session terminates when user logout,

  2. Session doesn't terminates before user logout.

Is there a way to customize FormsAuthentication or\and the Session State mechanism to Reach these goals?


Solution

  • There's no inbuilt mechanism because the reality is you want to keep users logged in for longer than you want to keep their sessions around for. Also, sessions are not meant to be guaranteed storage, and you should avoid any reliance on data being in session.

    Nothing happens on the server when an authentication cookie expires. There is no tracked state.

    You could have a 'logout' link and in the handler Abandon the session and SignOut from FormsAuthentication, but there's nothing that forces a user to log out from a website.

    Some people like Session, however most hate or come to hate it because its use is abused. Main reasons are Session overuse tends to be the cause of poorly performing servers, and incorrect Session use can create websites that won't scale.

    Avoid the use of Session if you can, and if you must use it, observe the recommendations in the MSDN article Improving ASP.NET Performance. Also have a look at Understanding session state modes + FAQ and in particular Q: Why isn't Session_End fired?