SessionID is same but session data are not same - asp.net

I created two different very simple apps (ASP .NET) and host on the local iis.
Both apps are open in same browser in two tabs. In first application (AppA) I store some data in Session (Session["name"] = "john") and in second application (AppB) I read this value. When I explore cookies (with FireCookie) I saw that SessionIDs for both applications are same. Also, In both apps SessionID is printed and are the same. When I try get this value in AppB from session (with correct key), session is empty, but session id is still same. In AppA session data are still alive.
Why session data are different when both apps ask web server (with same session id) to return data?

The sessions are not shared, because it are different applications. So even when they got the same id, they don't "know" eachother. Check out this article for a possible solution http://www.codeguru.com/article.php/c19357

Related

Session and Cookies asp.net

I was reading an article on asp.net session vs viewstate and after reading the article I got a doubt i.e. the article says if I create a session variable i.e.
Session("username")="username" this value is saved on webserver and webserver on start of first request creates a cookie and store it on a client machine and then retrieve the session variables for specific user based on the cookie value stored on client machine.
My doubts are - How and where does the session variables are stored on the server.
My understanding is based on the sessionID i.e. cookie value stored on client machine the webserver created a folder and for all the session variables created it create file and store the data i.e. For all the session variables stored on webserver there will be only one cookie stored on client machine- Please correct me if I am wrong in understanding to what I mentioned above.
ASP.Net allows you to configure where you want your sessions variables stored. The documentation on the different options you can use is available here:
https://msdn.microsoft.com/en-us/library/ms178586%28v=vs.140%29.aspx
The short version is that session variables are stored in memory with your application by default, but you can also use a separate process or even Sql Server. None of the options uses a folder on your disk, though. That would be slow. If you really want to use a folder on the server, you have to write your own custom provider.

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.

How to maintain the same session id across multiple web applications in ASP.NET

I have two identical applications setup on IIS on different virtual directories (I have done some workaround to ensure that they both have the same application name). Is there a way to share session id across two asp.net web applications?
Since I'm storing the session in StateServer, they should both be getting the same session data, however, a different session id is created everytime I go from application a to applicatino b. Wouldn't this happen in a load balancing scenario as well? Where when I go to www.test.com, it would redirect that request to server a, and then if I hit it again, it would go to server b, but since it's a different web application, it would create a new session id?
First, configure the sessionState element in your web.config to use cookieName="SOME_COOKIE_NAME_HERE" in both apps.
Then, just make sure the urls have the same TLD (top-level domain), i.e. app1.mydomain.com and app2.mydomain.com and you should be able to handle the Session_Start event in Global.asax and put this code:
HttpCookie cookie = new HttpCookie("SOME_COOKIE_NAME_HERE", Session.SessionID.ToString());
cookie.Expires = DateTime.Now.AddMinutes(20);
cookie.Domain = "*.mydomain.com";
cookie.HttpOnly = true;
Response.SetCookie(cookie);
Also, I would recommend that you go with the SqlServer SessionState Mode.
Initially i faced the same issue. What I did is, I overide the jsession id from each domain. I mean, If the user lands on domain1.com, set the same session id for domain2.com from iframe. and vice versa. With this, you can maintain same session across multiple domains.
You need to test the impact over multiple server over network with load balancer.
Is your goal to share the session state between 2 applications, not just the session ID? I believe the StateServer also uses the application path as well as the SessionID to store the data so even if the SessionID's were the same you still wouldn't be able to share the data. You might have to write your own session module.
Load balancing web apps don't have this problem because the application path is the same across cluster members.

What is the use of Session in web application/ASP.Net?

I am new to web technology, I am wondering about the use of Session.
What is the basic use of Session, is it only used for saving soma data or it has something else ?
Session is all about storing data across page requests. One of the downsides of HTTP (the core protocol of web applications) is that it doesn't store anything from one page request to another; you have to build all that in yourself. There are generally two places to store data: the browser or the server, and sessions are server based.
A session starts when you first log into a system and continues for as long as you stay on the site. When you close your browser (or perhaps log off, depending upon how it's configured) your session ends (there's usually a delay, so it ends after X minutes without activity). If you, as a web site developer, need to store some information about the user (name, address, shopping cart, etc), then session is often used as a place for that storage.Generally the reason for storing data in the session is for performance; reading from a database is relatively slow (compared to other actions a web page performs), so if you read the data once then store it in the session, you can make your site faster. The downside is that the more data you store in the session, the more memory you use on the server, so it's a trade-off between performance and memory usage.
In the above code, the session is being used to store some user details (name, email, etc). If those don't exist in the session when read, an empty string is returned.
Session is for storing user-specific data for a limited period of time - namely, a single session of activity:
[A] communication session is a semi-permanent interactive information exchange between communicating devices that is established at a certain time and torn down at a later time.
This is deliberately vague, since the details of what makes a "session" can be somewhat different from application to application depending on how it is used. For a typical web application, a user's session begins the first time they visit the site, and ends some time after the user has no longer made any requests, and is presumed to have left the site. Things like a shopping cart, which are user-specific, might go in the session object, since it follows the same user across requests. In ASP.NET, the Session is described:
ASP.NET session state identifies requests from the same browser during a limited time window as a session, and provides a way to persist variable values for the duration of that session.
Session is use for storing some data for limited priod of time is have use to send some information one page to other page without data base connectivity
like:
1st page:
Session["valiable name"] = textbox1.Text;
2nd page:
Lable.Text = Session["valiable name"].ToString();

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