66

In my asp.net website i am using asp.net form authentication with following configuration

<authentication mode="Forms">
    <forms loginUrl="~/Pages/Common/Login.aspx"
           defaultUrl="~/Pages/index.aspx"
           protection="All"
           timeout="30"
           name="MyAuthCookie"
           path="/"
           requireSSL="false"
           cookieless="UseDeviceProfile"
           enableCrossAppRedirects="false" >
    </forms>
</authentication>

I have following questions

  1. What should be timeout value for session because i am using sliding expiration inside form authention due to which session will expire before form authentication. How can i protect it?

  2. After formauthentication log out i would like to redirect page at logout.aspx but it is automatically redirect me at loginpage.aspx. How is it possible?

GaTechThomas
  • 5,421
  • 5
  • 43
  • 69
Hemant Kothiyal
  • 4,092
  • 19
  • 61
  • 80

2 Answers2

56
  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
}
Dmytrii Nagirniak
  • 23,696
  • 13
  • 75
  • 130
  • 2
    Thanks Dmitriy, My second question: As its written above inside
    that default page is "index.aspx" and login is "login.aspx". After login at my dashboard page when i remain ideal for 30 minute (timeout) and after that i click on any link i will automatically redirect to login page with following URL http://localhost:/virtualdir/Pages/Login.aspx?ReturnUrl=%2fvirtualdir%2fPages%2fDashBoard.aspx But here i would like to redirect page at logout page where i can say some logout information
    – Hemant Kothiyal Sep 24 '09 at 10:28
  • Can you show me example because in my case i take scenario where i set formauthentication timeout= 2 minute while session timeout= 6 minute and after 3 minute when i click on link It doesn't debug anywhere even not at "AcquireRequestState" Please help? – Hemant Kothiyal Sep 24 '09 at 13:07
  • Upps. Sorry, the timeout for the FormsAuthentication should be twice longer than Session's one. Corrected that. AcquireRequestState and AuthenticateRequest should always be triggered (no matter what). Make sure you correctly subscribed to these events on the HttpApplication class. – Dmytrii Nagirniak Sep 24 '09 at 13:32
  • Thanks, Can you clear another doubt. I have confusion that if i set sliding expiration=true in "Formauthentication" then automatically sliding expiration works for session timeout also or not? Does sliding expiration works for session time out? – Hemant Kothiyal Sep 24 '09 at 14:05
  • FormsAuthentication expiration (absolute or sliding) is not related to Session expiration in any way. The Session has no absolute expiration and always expires "sliding" way. – Dmytrii Nagirniak Sep 24 '09 at 22:55
  • 32
    Are you sure that you want to have Session.Timeout < FormsAuthentication.Timeout * 2? This means that the Session can be abandoned while the user is still logged in. Anywhere that references Session variables will start having NullReferenceExceptions. – Dominic Zukiewicz Oct 20 '10 at 15:31
  • 2
    Is the condition `ticket.Expiration > DateTime.Now` correct? I think it needs to be the other way around so the the redirect occurs when the current DateTime is greater than the forms authentication ticket expiration. – Daniel Ballinger Jul 02 '12 at 02:05
  • 4
    Agree with Dominic's point. Having forms auth persist while clearing the session has a valid purpose (it's probably the way most apps want to go). However, I have a (secure mobile-web) app where I wanted just the opposite, and use frequent forms auth as an identity challenge. I'd like this answer to include a justification or example to support the expiration model you have suggested. – Jason May 23 '13 at 22:29
  • 8
    I was confused on letting the forms auth expire later than the session. This doesn't make sense to me, but here is another supporting blog post to agree. Also there is a link to a MSDN article trying to re-enforce the solution. http://itworksonmymachine.wordpress.com/2008/07/17/forms-authentication-timeout-vs-session-timeout/ http://support.microsoft.com/kb/910439 – MADCookie Feb 06 '14 at 18:47
  • For anyone stumbling across this question refer to this documentation from MS - it has really good details regarding FormsAuthentication Timeout settings https://learn.microsoft.com/en-us/aspnet/web-forms/overview/older-versions-security/introduction/forms-authentication-configuration-and-advanced-topics-cs#specifying-the-tickets-timeout-value – Naren Feb 20 '19 at 20:51
  • ASP.NET MVC event ? I want not expires never el auth cookie, only in Logout - Sign out ? – Kiquenet Apr 06 '19 at 10:21
28

For sites that have a session dependency, you can simply sign out of a stale authentication with the session start event in the global.asax:

void Session_Start(object sender, EventArgs e)
{
  if (HttpContext.Current.Request.IsAuthenticated)
  {

    //old authentication, kill it
    FormsAuthentication.SignOut();
    //or use Response.Redirect to go to a different page
    FormsAuthentication.RedirectToLoginPage("Session=Expired");
    HttpContext.Current.Response.End();
  }

}

This makes it so that new session = new authentication, period.

b_levitt
  • 7,059
  • 2
  • 41
  • 56
  • 1
    It seems forceful, but was a good option for us where having the session in place is essential at the moment. – Alex KeySmith Jul 12 '12 at 15:20
  • 3
    I'm not sure I'd call it forceful. It simply marries the session authentication states together. Sure, a more robust option would be to restore session given the authentication token. But if session restoration was an afterthought (ie spread all over the place), the easiest solution is to get the user back on a known path (logging in). – b_levitt Aug 13 '13 at 19:47
  • True, this is the route we have taken until we can make sessions recreate themselves on the fly. – Alex KeySmith Aug 14 '13 at 09:16