views:

76

answers:

2

What is the best way to detect when a redirect to the login page occurs due to a forms authentication timeout in order to display a meaningful message?

<authentication mode="Forms">
    <forms loginUrl="~/Login" timeout="15" slidingExpiration="true"/>
</authentication>
A: 

There's nothing out-of-the-box allowing you to achieve this. You could for example write a custom Authorize attribute that will check if the authentication cookie has expired.

Darin Dimitrov
So how would the code in the attribute detect that a timeout had occurred?
CodeGrue
`FormsAuthentication.Decrypt(authCookieValue).Expired`
Darin Dimitrov
I confirmed that after timeout, Request.Cookies[".ASPXAUTH"] returns null, so you cannot access the expired property.
CodeGrue
+1  A: 

After fiddling for quite a while I came up with this hackish solution that works. I would love to hear a more elegant solution.

1) Create a cookie after forms authentication:

   // log the user in
   FormsService.SignIn(userId, false);
   Response.Cookies["WasLoggedIn"].Value = "true";

2) On the login GET action, look for this cookie existing and the authentication cookie not existing:

   if (Request.Cookies[".ASPXAUTH"] == null && 
       Request.Cookies["WasLoggedIn"] != null)
   {
      // forms authentication timed out
   }
CodeGrue