Session state asp.net life span - asp.net

I have read that asp.net session variable last by default 20 minutes of inactive browser.
What happens if the user logs out and immediatly logs in? Or closes the browser and restart it? The session state "dies" ?
If not- what is the alternative to make it die on evey log-out or browser closing?
Thanks

Session state relies completely on the presence of a cookie being provided by the browser for each request in the 'session'. When the server takes receipt of the cookie on each request it then checks if the default 20 mins has passed since the last request.
Therefore the answers to your questions:
What happens if the user logs out and
immediatly logs in?
The cookie is marked as invalid by the server on logout and is assigned a brand new one when they log back in
Or closes the browser and restart it?
Provided the session hasn't expired it won't make any difference (as the browser will still send the cookie along with each request)
make it die on evey log-out or browser
closing?
You can't make a cookie 'die' although you can set it's expired date to the past. There is no way you can detect the user closing their browser.

Whether the session remains active relies on two things:
Whether the Session is still alive on the server (your 20 minute timeout, or you programmatically abandoning the session)
Whethet the client (browser) transports the Session cookie to the server, so the session can be identified.
The Session cookies are served as non-persistent cookies, meaning that they should be maintained by the browser for one session (of the browser), so they should not be sent after you close the browser and restart it. But in reality, it is entirely up to the client browser implementation.
The lesson here: Yes, Sessions expire when the average user closes his browser. But you can't and shouldn't rely on it for anything important.

On log out you might have to clear session manually.
New instance of browser should have new session.

Session.Abandon() will flush all your session. Call this when the user logs out. So every time he logout and logs in, new session will be created. Session TimeOut and Closing a browser will automatically result in a new session next time.

A session "dies" after 20 minutes of inactivity (by default), or if it was cleared by the programmer.
To clear a session, you call the Abandon method on it. Do that on logout.
There is no simple way to detect that a browser window has closed (you can use Ajax to poll from the browser, for example), since the web is stateless. However, if this happens (and no other instances of the browser are still open), when the user starts a new instance and accesses your website, he will get a new session (though the existing one will linger on till it times out).

I'm assuming when you want the user to be logged out - you want the Session to be destroyed, not just the Session Key / Value pairs to be removed.
Calling:
Session.Abandon();
Will destroy the Session.
http://msdn.microsoft.com/en-us/library/ms524310(v=vs.90).aspx

Related

How does ASP.NET server know when a session is terminated?

I understand that Session object is used to store data per session. I did the following experiment:
Open browser and visit an aspx page A, which saves some data to Session object.
Keep the browser open and open another tab to visit an aspx page B which display the session data. And it displayed just as I stored in step 1.
I close the browser and re-visit the page B, the stored data is gone.
From 3, it seems server side somehow detect that I (the client side) has terminated a session. But as I checked with Fiddler, there's no bits sent to the server when I close the browser in step 3.
So how could the ASP.NET application possibly know my step 3 request is for a new Session?
And how is session defined? Do different tabs always belong to the same session?
ADD 1
Although the session data can be displayed in page A and page B, the session IDs displayed in them are different. Why?
Correct
The session id in page A and page B are the same. I am not using InPrivate browsing.
ADD 2
There's indeed a Cookie for session ID:
ASP.NET_SessionId=lmswljirqdjxdfq3mvmbwroy; path=/; domain=localhost; HttpOnly
It was set when a POST request is responded.
So I did another experiment, I close the browser (Fire Fox) and as expected, the Cookie no longer exist. I manually create the cookie in hope of "the faked Cookie could bring back the old session." But Fiddler indicates that the manual cookie didn't get sent at all.
Fiddler says:
This request did not send any cookie data.
So is it possible to fake a cookie and restore an previous session?
And how long does a session live on server?
When the server starts a new session, it generates a new identifier for the session. The session data is stored under this identifier / key in your session provider (can be in-memory, in SQL Server or something else entirely, depending on your configuration - this is usually configured in web.config).
At the same time, the server sends a cookie to your browser (at least in the default setup). This cookie contains the identifier for your session. That is how the server can correlate your requests to your particular session: in every request, your browser will send the session cookie along. The server retrieves the identifier from the cookie and looks up your session data using the identifier.
The session cookie is non-persistent, which means that the cookie will be deleted when the browser is closed. That is why it looks like the session was deleted: the session data still exists on the server, but because the session cookie has been deleted, the browser won't send along a session cookie, so the server will consider this to be the beginning of a new session, create a new session identifier etc. Thus, the server doesn't really know when a session ends, it just knows when a session begins. That is why, in the default SQL Server-backed setup, a scheduled job will purge inactive sessions - otherwise the session data would linger in the database forever.
For more on sessions, using sessions without cookies, session configuration, providers etc., see MSDN.
As to whether sessions are shared between browser tabs: this really comes down to whether cookies are shared between tabs. I think cookies are shared across tabs in all major browsers and I would assume it would be rather confusing if they weren't, but there is nothing preventing someone from creating a browser where cookies aren't shared across tabs.
EDIT 1
If you delete the session cookie, you could in theory recreate your session by recreating the cookie. This is not a security issue per se, because you are recreating data you already have access to. However, if someone else were to recreate your session cookie, that would be a security issue. You can google "ASP.NET session hijacking" if you want to look into this.
EDIT 2
The session basically lives on the server until something purges it. Thus, the lifetime of the session depends on where you store it. If you store it in memory, the session will be deleted when the application is recycled (could be because you recycle the app in IIS or because the server is restarted). If you store it in SQL Server, the session data will live until a job deletes it because it hasn't been accessed for a while (sorry, I don't remember the details, but you can probably google them). If you store your session data in Azure table storage, they will likely never be purged.
Note
Two important details of ASP.NET session state are often overlooked:
When the session is stored outside the process (say, in SQL Server), the data you want to store must be serializable.
To prevent race conditions when accessing the session data, requests accessing the session will be serialized, that is, they will not execute concurrently.
Further details may be found in the MSDN article "Underpinnings of the Session State Implementation in ASP.NET"
This article provides more details about ASP.NET Session (http://msdn.microsoft.com/en-us/library/vstudio/ms178581(v=vs.100).aspx)
The idea is simple.
When you visit a page, a session ID is generated and set as a cookie. A timer is started for that session ID too.
As you keep coming back, the timer is reset. If you wait long enough before requesting another page, the timer will expire and your session will not be valid. At that point a new session will be generated.
To Answer your questions:
If you open multiple tabs, they will "share" the session. Because your browser is sending the session cookie from all those tabs.
However, if you open Firefox and Chrome. These two browsers will not share the session. Since, they don't share cookies.
When you close your browser, your session is still valid. And if you visit a page on the site before the session has expired, you will not get a new session. That is why, it is suggested to always log out. This way the site knows that you're leaving and it will destroy the session on your behalf.
Q: Although the session data can be displayed in page A and page B, the session IDs displayed in them are different.
A: Are you sure? The session ID should be the same for all pages. It will be different if you access page A from one browser and Page B from another browser.
ADD2
It is possible your browser's setting is to destroy cookies on windows close. Please double check that in options it's set to remember history.
Cookies can be forged. If an attacker can get the session ID, they can forge a cookie at their end. I'm not sure if Fiddler allows you to create a cookie manually. You will need to dig through the docs. Or maybe someone else here can answer this questions.

Finding time until timeout fires in asp.net

First of all, let me ask this:
Let's say that a web application has its timeout set to 10 minutes. For some reason, the user is idle. If he/she returns and press any key or moves the mouse, it resets the timeout? Or it is based on the last time it went to the server?
And now the second question: is there a way to find the time until the user gets logged off due to innactivity?
From MSDN:
The Timeout property specifies the time-out period assigned to the
Session object for the application, in minutes. If the user does not
refresh or request a page within the time-out period, the session
ends.
So in answer to your question, the timeout is reset if the user sends a request to the server by either navigating to another page or refreshing the current page (or possibly by using some form of AJAX keep-alive method (See this question)).
This article on Code Project provides a pretty good overview of Sessions within ASP.net
For your second question, this gets a little complex as the session timeouts are managed by IIS so your page has no idea how much longer the session will be valid for. I have seen examples where another timer is placed with in the page itself and when this reaches a certain low value the user is warned that their session is about to expire. The page could then refresh (resetting the session timeout value in IIS) and the user wouldn't be logged out / lose their session.
However, this will require the session timeout value that is configured is kept in sync with the value configured in the JavaScript function.

How does an ASP.NET session expire when the browser is closed?

As in the title, I wonder how a session expires when the client's browser is closed?
The session lives on the server. It expires when the browser is closed long enough or isn't used long enough or when a new request arrives that either doesn't contain the cookie, or the cookie refers to a sessionid that's too far in the past (default timeout is 20 minutes).
When there's no connection, the session is removed from memory at an undetermined moment in time, or when you programmatically call .Abandon on the session.
When a session is not available or a session has been cleared because it had timed out, a new session object will be created. When this is the result of a browser request, the Session_End event will trigger in the global.asax file.
Note: the actual way a session is timed out and cleared depends. I.e., inproc sessions will be destroyed and trigger a Session_Timeout. Out-of-proc sessions do not, and will be destroyed in a state server or an SQL server. In the latter case, a stored procedure is called regularly to clean up. The stored procedure is only called when there's activity on the server, which means that sessions can live longer than 20 minutes in (database) memory, but will be destroyed on next access.
As defined on the web server (e.g. IIS). The typical default is around 20 mins after the last access (i.e. web request for that session). At this point the session is cleared, so apps need to use either cookies or some server-side state to work out who someone is for return visits to make the experience seamless.
The browsers temporary cookies are deleted and the server kills the session data after a predetermined amount of time since last access.
It does and doesn't. It lives on on the server until it times out (usually 20 minutes). But since it's kept alive in the browser using a session cookie, that expires as the browser is closed, the user will not be able to reconnect to that session again.

How to abandon session if user X's out of browser?

Is there a way to do a Session.Abandon() when the user just kills the session by X'ing out with the little red X box in the upper right corner? I am seeing situations where after an "X out", the user comes back in and it seems like session variables are still present? I guess explorer keeps them intact? (I am unsure of this).
You can try doing an AJAX type callback in the OnUnload event - however, as someone else mentioned you'd have to be aware of other tabs being open (not easy), and it still won't guarantee you get that event.
There's a combination of things to do to get a similar type of effect.
Session Cookie should have a null/empty expiry time. This ensures the browser deletes the session from it's end after the browser is closed.
The ASP Session can be set with a short SessionState timeout value. This means if there's no client activity within that period, the Session will expire.
The side effect of this is that if a user is just looking at the site, and not performing activity (regardless of whether the browser is still open) - the session can expire.
This can be worked-around by having a Javascript timer periodically ping back to the server with an AJAX call or similar. The side effect of THIS is that it generates more site traffic.
The server is typically not aware of such events on the client. The only way the server can be notified about anything is if there is a request sent back to it. I guess you could create such a notification in a JavaScript, but then you should also keep in mind that the session in mind that the session is not per-page but (usually) per user, which means that you would need to keep track of how many tabs/windows the user has opened so that you don't kill the session when you should not.
Personally, I usually try to design the web apps so that they live well with the default handling of sessions, either providing a specific "Logout" command that will kill the session, or simply let it hit the timeout and die.

Where to set session timeout?

The application sets session.timeout in Application_AcquireRequestState event handler.
Before session expires, there is notification window popping up. It resets session timeout to, say, 3 minutes (normally, it is 30 minutes), through Application_AcquireRequestState.
The notification offers user an option to extend session for another 30 minutes. If user clicks yes, it will reset session timeout for 30 minutes through the previous event handler.
The problem is, though user clicks yes, and session timeout is set correctly, session seems timeout before the set time. This only happens after notification.
The suspicion is when it hits Application_AcquireRequestState, the timeout is already calculated for this request. The new timeout value will be used for next request. So when user clicks yes to extend session, the timeout for current request is not 30 minutes away, it is only 3 minutes away, due to timeout set by the notification window. The yes will only be in effect if user sends another request.
(Notification window has its own timing object)
Can anyone verify this? or point me to a good resource to explain how asp.net manages this?
Thanks!
Session.Timeout is a global setting within the application.
If you're setting the users Timeout to 3 minutes when you pop the window notifying the user that they are about to be logged out, and they don't respond, your Session.Timeout will stay at three minutes until another user resets it - is it possible that this is happening?
Zhaph, the problem is when user clicked "Yes" to extend the session, then walk away.
I think I finally nailed down the problem.
It was as I suspected, but only in "SQLServer" mode. When request comes into Application_AcquireRequestState, the session is already extended (can be verified in ASPState database, ASPStateTempSessions table). If user clicked "Yes", though the new time out value is set, it won't be in effect until next server request. If user walked away without another click, session timed out with the previously set timeout value, which is 3 minutes.
In "InProc" or "StateServer" mode, the session objects are managed by cache, whose expiration can be reset only further in the future but not shrink back to more current time (or it will be ignored).
I use a much simpler mechanism. I don't have the popup extend the session at all. I use a session with a sliding window and when the user clicks the "OK" button in the session expiration notification, it makes an AJAX request back to the server updating the sliding window.

Resources