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

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.

Related

what will happen after browser closing

We know that when we closed the browser, session gets destroy.
Please help me with below query.
Lets say i have clicked on submit button on my registration page and internally it get called SQL store procedure, which takes more time to execute..
on same time if i closed the browse what will happen?
Does my sql connection still available ? if yes then after closing browser still my store procedure is in execute mode?
when exactly the session get destroy?
Would like to know more about this life cycle , Thanks
First have this in mind.
The session is connected with a cookie on the users browser.
The session have a time out.
If anything of this two gone, the session is gone, so let see them analytically.
Cookie
If the cookie is a session cookie (temporary), then is gone when the user close the browser, if its not temporary then is gone when it expires, or of course if the user clears it, or if the user is in private mode is not even saved.
So when the cookie that is connected with the session is gone, you lose the session
The session can be lost even if the browser is not been able to read the session cookie for other reasons.
Session Data on server
The session that is connected with the cookie, is a Dictionary of data that lives on server.
The session have a timeout, so if the user did not update the call to the server inside this time, the server kills the session data on server.
Also, note that the session can be served on the SQL Server, or in a service that runs on background and keeps that data in memory.
If you save the session data on the memory, then they can be lost even before the session times out, from IIS recycle, from the service itself that clears it for their reasons.
Server Side Time Out
If you call a long time function, and the users ends their connection, then the procedure will be continue to runs until either ends either gets a time out. This is not so safe if your process takes 10 minute to execute, you probably gets timeout and never ends correct, even if the user is still connected. If you talk for few seconds, then its relative ok, the procedure will executed even if the users close his browser side.
Check the time out of the page and the time out of the sql server side. If you end well with the user connected, you will end the same and if the user close their connection in the middle.
Have in mind that in a heavy multi user call situation you may have a problem from the session locks, read this q/a ASP.NET Server does not process pages asynchronously
So take care the procedure to not take more than few seconds.
Last words
The most "secure way" to not lost your session in a time period is to use well setup cookie, that is not temporary and keep their life for some months (google keeps their cookie for two years), and use SQL Server to saves your session data.
More details to read at:
ASP.NET State Management Recommendations
Session would not retain values and always return null
Keeping a related ASP.NET application's session alive from another ASP.NET application
ASP.NET Session State Overview

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.

setMaxInactiveInterval on OC4J isn't accurate

I've a servlet app deployed in side oc4j.
I am trying to invalidate the user session after 1 minute using:
session.setMaxInactiveInterval(1 * 60);
But What happens is that It takes over 1 minute (and may reach 1 min and half) before the session get destroyed.
Is this an implementation issue, or what?
You seem to be checking the destroy by waiting until HttpSessionListener#sessionDestoryed() get called instead of actually sending a HTTP request to the server after exactly 1 minute.
The session destroy is on most servers managed by a background job which runs at intervals, which can be each minute or more depending on server make/version, configuration and possibly also load. This job checks all open sessions whether it has been expired or not and sweeps the expired ones accordingly. Thus, it is not true that the session destroy is immediately called on the same second as the session is expired as long as the client hasn't sent a request. This background job does not run every second, it would have been too CPU intensive.
The session destroy will however be immediately called whenever the server retrieves a request with a session ID while the session is still present in server's memory but is been expired.
So, you'd either have to accept it or to change your testing methodology.

Session state asp.net life span

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

How do I explicitly set asp.net sessions to ONLY expire on closing the browser or explicit logou?

By default the session expiry seems to be 20 minutes.
Update: I do not want the session to expire until the browser is closed.
Update2: This is my scenario. User logs into site. Plays around the site. Leaves computer to go for a shower (>20 mins ;)). Comes back to computer and should be able to play around. He closes browser, which deletes session cookie. The next time he comes to the site from a new browser instance, he would need to login again.
In PHP I can set session.cookie_lifetime in php.ini to zero to achieve this.
If you want to extend the session beyond 20 minutes, you change the default using the IIS admin or you can set it in the web.config file. For example, to set the timeout to 60 minutes in web.config:
<configuration>
<system.web>
<sessionState timeout="60" />
... other elements omitted ...
</system.web>
... other elements omitted ....
</configuration>
You can do the same for a particular user in code with:
Session.Timeout = 60
Whichever method you choose, you can change the timeout to whatever value you think is reasonable to allow your users to do other things and still maintain their session.
There are downsides of course: for the user, there is the possible security issue of leaving their browser unattended and having it still logged in when someone else starts to use it. For you there is the issue of memory usage on the server - the longer sessions last, the more memory you'll be using at any one time. Whether or not that matters depends on the load on your server.
If you don't want to guesstimate a reasonable extended timeout, you'll need to use one of the other techniques already suggested, requiring some JavaScript running in the browser to ping the server periodically and/or abandon the session when a page is unloaded (provided the user isn't going to another page on your site, of course).
You could set a short session timeout (eg 5 mins) and then get the page to poll the server periodically, either by using Javascript to fire an XmlHttpRequest every 2 minutes, or by having a hidden iframe which points to a page which refreshes itself every 2 minutes.
Once the browser closes, the session would timeout pretty quickly afterwards as there would be nothing to keep it alive.
This is not a new problem, there are several scenarios that must be handled if you want to catch all the ways a session can end, here are general examples of some of them:
The browser instance or tab is closed.
User navigates away from your website using the same browser instance or tab.
The users loses their connection to the internet (this could include power loss to user's computer or any other means).
User walks away from the computer (or in some other way stops interacting with your site).
The server loses power/reboots.
The first two items must be handled by the client sending information to the server, generally you would use javascript to navigate to a logout page that quickly expires the session.
The third and fourth items are normally handled by setting the session state timeout (it can be any amount of time). The amount of time you use is based on finding a value that allows the users to use your site without overwhelming the server. A very rough rule of thumb could be 30 minutes plus or minus 10 minutes. However the appropriate value would probably have to be the subject of another post.
The fifth item is handled based on how you are storing your sessions. Sessions stored in-state will not survive a reboot since they are in the computer's ram. Sessions stored in a db or cookie would survive the reboot. You could handle this as you see fit.
In my limited experience when this issue has come up before, it's been determined that just setting the session timeout to an acceptable value is all that's needed. However it can be done.
This is default. When you have a session, it stores the session in a "Session Cookie", which is automatically deleted when the browser is closed.
If you want to have the session between 2 browser session, you have to set the Cookie.Expired to a date in the feature.
Because the session you talk about is stored by the server, and not the client you can't do what you want.
But consider not using ASP.NET server side session, and instead only rely on cookies.
Unfortunately due to the explicit nature of the web and the fact there is no permanent link between a website server and a users browser it is impossible to tell when a user has closed their browser. There are events and JavaScript which you can implement (e.g. onunload) which you can use to place calls back to the server which in turn could 'kill' a session - Session.Abandon();
You can set the timeout length of a session within the web.config, remember this timeout is based on the time since the last call to the server was placed by the users browser.
Browser timedout did not added.
There's no way to explicitly clear the session if you don't communicate in some way between the client and the server at the point of window closing, so I would expect sending a special URI request to clear the session at the point of receiving a window close message.
My Javascript is not good enough to give you the actual instructions to do that; sorry :(
You cant, as you can't control how the html client response.
Actually why you need to do so? As long as no one can pick up the session to use again, it would expire after that 20 minutes. If resources does matter, set a more aggressive session expiry (most hosting companies did that, which is horribly annoying) or use less objects in session. Try to avoid any kind of object, instead just store the keys for retrieving them, that is a very important design as it helps you to scale your session to a state server when you get big.
Correct me if I am misreading the intent of your question, but the underlying question seems to be less about how to force the session to end when a user closes the browser and more about how to prevent a session from ending until the browser is closed.
I think the real answer to this is to re-evaluate what you are using sessions to do. If you are using them to maintain state, I agree with the other responses that you may be out of luck.
However, a preferred approach is to use a persistent state mechanism with the same scope as the browser session such as a cookie that expires when the browser is closed. That cookie could contain just enough information to re-initiate the session on the server if it has expired since the last request. Combined with a relatively short (5-10 min) session timeout, I think this gives you the best balance between server resource usage and not making the user continually "re-boot" the site.
Oh you have rewritten the question.
That one is absolutely feasible, as long as javascript is alive. Use any timed ajax will do. Check with prototype library http://www.prototypejs.org PeriodicalExecutor or jQuery with the ajax + timer plugin. Setup a dummy page which your executor will call from time to time, so your session is always alive unless if he logouts (kill the ajax timer in the same time) or close browser (which means the executor is killed anyway)

Resources