views:

571

answers:

2

When you have forms authentication setup to redirect to login.aspx when accessing a protected page, what's a good way to detect in login.aspx whether the user was sent there because they haven't logged on yet, or because their forms auth ticket is expired? I'd like to display a "you've timed out" message.

(I do not mention the word session in this question, because ASP.NET treats them so distinctly, however, if there is a good solution that involves session, I'm all ears)

I've solved this in the past by having another cooke "hasloggedin" set when a user logs in and then checks to see if that exists to determine if it's a timeout and then display an appropriate message. But, this has to be a common problem?

+2  A: 

Forms authentication will automatically append a URL parameter 'ReturnURL', indicating what page (if any) triggered the redirection to the login page. Most websites have a 'Default.aspx' or 'index.html' etc as the default page. You can check the ReturnURL to see if it contains the default page, or some other page in your application.

EXAMPLE:

string refererURL;
if (page.Request.QueryString["ReturnURL"] != null)
{
    refererURL = page.Request.QueryString["ReturnURL"].ToString();
}

//Check to see if user was redirected because of Timeout or initial login
//Where "Default.aspx" is the default page for your application
if (refererURL != "" && refererURL != (ResolveUrl("~") + "Default.aspx"))
{
    //Show HTML etc showing session timeout message 
}
else // User redirected here to to initial login
{
    //Show HTML showing initial login HTML message etc
}
PortageMonkey
Good idea. This may work great for my current app, but for others I've done, there have been links on anonymous pages to pages that require authentication, and so the returnurl isn't enough to tell the difference between a timeout or first attempt at a protected age. But, I think this should work in many cases, and combining it with looking at the actual value of returnurl should make it even better. Thanks for the reply.
RyanW
+2  A: 

Right. How do you determine the difference between: 1. User attemtped to access a secure page while not logged in. And... 2. User was logged in, then login expired, and user was redirected to login page.

Geoff