Dave
Dave

Reputation: 2562

Stop site reusing session id on expiry

I want to be able to log when a user ends their session on our application and record whether it was a sign out or a the session expired. I am using

cookies.Add(new HttpCookie("ASP.NET_SessionId", ""));

to set a new sessionId on sign out, but when the session expires, the sessionId is reused if the browser instance is not closed. In my web.config I have used

        <sessionState mode="InProc" timeout="1" cookieName="session" regenerateExpiredSessionId="true" />

but still get sessions reused.

I can't kill the cookie in Session_end() because I don't have access because there is no HttpContext or request, so I can't reset it that way.

Does anyone have any ideas how I can force a new sessionId from the Global.asax.cs file?

Thanks

Dave

Edit - This is currently on our development environment, but our production application uses a state server for session. Not sure if this should make a difference to the sessionId Allocation (I know that I'll need to use an custom IHttpModule rather than Session_end)

Upvotes: 2

Views: 3683

Answers (2)

David
David

Reputation: 2795

Firstly, you will be unable to track when sessions end in production because the global Session_End is not guaranteed to fire when using any state mechanism other than InProc.

Session cookies are non-persistent, so the only way you can achieve the problem you are mentioning is if the user leaves their browser instance open and their session times out due to inactivity, then re-visits the page. You could record the session id in Session_Start as well as Session_End and your database log would be more robust as you would be able to identify timeout/relogin behavior.

You can use Session.IsNewSession to detect if the current session was created with the current request. (Regardless of what the provided sessionid id is).

If you are using session id to track whether the user is "logged in", you should avoid that and instead use the asp.net auth cookie which can have a configured timeout. (meaning the cookie itself has an expiration that is refreshed on each view, but after the timeout, the cookie will be discarded by the browser, thus requiring a re-login.

Upvotes: 4

Ray
Ray

Reputation: 21905

According to the docs on the RegenerateExpiredSessionId property:

By default, only cookieless URLs are reissued when RegenerateExpiredSessionId is enabled

So, unless your are using cookieless sessions, you are out of luck

What are you doing with these session ids that you require new ones? Storing them in a db or somewhere for later lookup? If so, maybe you should look at using some other kind of id that you can control (like an identity column on sql server).

BTW - do you really want your session to time out in one minute, or is that just a testing thing?

Upvotes: 4

Related Questions