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

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.

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

Session lifecycle question

I'm a little confused about the life cycle of the session in ASP.NET, here is my test case.
A user logs in, I save some info to a session variable (e.g. Session["bob"]="bob") then I do an "IIS reset". The user is still logged in, but the session data is null (e.g Session["bob"].ToString() throws a NullReferenceException.
I expected the session data to still be around. Is there something I can do, other than log out the user? I expected the session data to be around as long as the user is still logged in.
Any good links so I grok what's going on, as well as any help with the actual issue is greatly appreciated. I tried to Google this, but wasn't able to frame the question in a way to get what I wanted.
The behavior you are seeing - where the Session contents do not survive an IIS reset event - is due to where the Session values are stored. By default these values are stored within the memory of the ASP.NET "Worker Process", which is the program which runs your ASP.NET web site.
When you perform an "IIS reset" you shut down the entire IIS server, including the ASP.NET Worker Process. This means that the contents of the Session are removed from memory. Your user still appears to be logged in because that is controlled by the cookie stored in their browser. If the cookie is still valid, the login is.
If you wish your Session state to survive an IIS reset (or anything else which causes the ASP.NET worker process to restart) you'll need to store your Session objects in another place. This is fully supported by ASP.NET by using different Session storage "Modes". Read about those in the MSDN article "Session-State Modes".
For a general overview of the Session, check out the "ASP.NET Session State Overview" article on MSDN.
yah its right but some time its happen then session no remove properly at that time
you have to check session like
If Session("username") = nothing then
Response.redirect("~/default.aspx")
End if

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

What is the difference between ViewState,Application and Session of a Page?

Please anyone explain me the difference between ViewState,Application and Session of a Page ?
Quick one liners - if you want more detail, just ask
ViewState is the variable that holds the current state of the page, which is held in a hidden field in the page (used frequently)
ApplicationState is a variable you can store values in during the life off the application (may get cycled periodically, and without your knowledge) (used less-frequently)
Session is the variable you can write to that will persist from the moment they hit your site until they close the browser. (barring any timeouts). (used frequently)
A great article :
How to Choose From Viewstate, Session, Application, Cache, and Cookies
Some good discussion about the difference between Session and Viewstate : Session Vs ViewState
Session state is saved on the server.
Session state is usually cleared after a period of inactivity from the user.
Can be persisted in memory, which makes it a fast solution. Which means state cannot be shared in the Web Farm/Web Garden.
Can be persisted in a Database, useful for Web Farms / Web Gardens.
Is Cleared when the session dies - usually after 20min of inactivity.
ViewState is saved in the page.
The view state is posted on subsequent post back in a hidden field.
Is sent back and forth between the server and client, taking up bandwidth.
Has no expiration date.
Is useful in a Web Farm / Web Garden
SESSION Variables are stored on the server, can hold any type of data including references, they are similar to global variables in a windows application and use HTTP cookies to store a key with which to locate user's session variables.
VIEWSTATE Variables are stored in the browser (not as cookies) but in a hidden field in the browser. Also Viewstate can hold only string data or serializable objects.
When we use view state to design a web application it retains it's state consistently, in it's current position. If we use session then it does not retain it's state, so when we refresh the browser it starts from the initial page.

Basic: How is the session id created?

Does IIS create the session id when a request is received and where is that saved (client or server)?
How does server recognize that the request is coming from the same user/session?
The answer to your first question is Yes -- if sessions are used, and Both.
A cookie is a short bit of text passed back and forth between client and server with every request/response.
IIS generates a session id, saves it, and any associated data, and passes the in a cookie to the client (browser).
When the client makes another request, it sends the cookie, containing the sessionID back to the server. The server can then look at the cookie and find the session (and the associated data) which is saved on the server.
In ASP.net, there are multiple places for the session to be saved, but it's always within the server infrastructure.
The default is the memory of the IIS Process. This means: if you reset IIS (or the whole PC) or even just the application pool within IIS, all sessions are deleted, and the session data is lost forever. Also, if you have a LOT of sessions and store a lot of data in each session, the process will require a lot of memory, which can be a problem. This is called "In-Proc" Sessions.
The main alternative is a SQL Server Database. That way, sessions are kept even after a restart and it does not really matter how large each session is. The main downside is the added latency: Fetching data from a database is slower that the In-Proc solution of course.
There are also some other methods how to store sessions (including the option to write a completely new session provider), but the two common ones are "The Memory of the Server" and "A MS SQL Database".

Resources