views:

224

answers:

3

When the users login on my asp.net website (through FormsAuthentication), I store some information about them in the current session such as their UserId, FirstName and other very basic variables that I need frequently in various web pages.

The problem is that even if the session timeout is set to be longer than the FormsAuthentication timeout, I've noticed that sometimes the current session is reset (ie session=null).

1) I don't understand why it happens. Any ideas?

2) When this happens, the users are still logged in (FormsAuthentication has not timed out yet) but their current session doesn't contain any data anymore. What I would like to do is that when the current session times out, they're asked to login again. To do so, I would need to detect the session timeout and, when it occurs, log them out. How can this be done?

3)This seems a bit overkill. Can't I simply store whatever I store in the session (UserId, FirstName,etc) directly in FormsAuthentication? if so, how? This way I will have access to those values while they're still logged in regardless of the current session (which will not be used anymore in this case). Do you see anything wrong with this logic? If not, how can this be done?

A: 

I thought the UserID was in fact stored within the Membership system? Can't you get enough information from HttpContext.Current.User?

You can use Profile properties to store other pieces of information. See this page for more info.

Tomas Lycken
+1  A: 

We faced same problem and the reason is, FormsAuthentication and Session are two different thing. FormsAuth sets cookie and cookie is transmited with each request, but your Session may get distroyed if IIS worker process recycles or crashes and recovers or IIS restarts. Your cookie for FormsAuth remains alive but your session will not. Thats why OnAuthenticate you should simply recreate session if session values are not present. One if statement overhead is necessary here.

check this out FormsAuthenticationModule .

This will allow you to intiailize your session values if they are not initialized, you should check and initialize in this code in case if session may get destroyed.

Akash Kava
A: 

You have run head on into a common trap, mixing asp.net provider based features with the feature (session) that they were designed to replace. lol.

Use Profile provider to store incidental bits of data regarding the user. It may seem to be more work having to define the fields in config but it reduces code smell by not having arbitrary string keys scattered through your application. There are other benefits but using the Profile provider will solve your problem correctly.

Sky Sanders