How does a server maintain the state of a session with a client? - asp.net

I'm reading about session management in ASP.NET and I'm a bit confused.
This is what I understand:
When a client starts communication with my application, a session is created and the state of the session is maintained in a session object on the server.
The browser gets a cookie with the session ID and every request that he wants to make with relation to the session needs to be sent with that cookie.
The session ends when some rules are met.
As long as the session is alive, the browser must have the cookie and the server must maintain the session object in memory.
Is this how it works or am I mixing things up? I read somewhere that the server can maintain the state with the cookie only but I don't understand if it's correct or possible (the last point in the bullet list).

You've got it right, that's how it normally works. In terms of cookies ASP.net does have a way of offering a session without a cookie, which it achieves by basically putting your cookie into the URL instead. That might be what you're thinking of.
Normally this isn't a great idea, it makes session hijacking as simple as copy pasting the victims URL into your own browser.
There are two ways that session state can store the unique ID that associates the client with a server session: by storing an HTTP cookie on the client or by encoding the session ID in the URL. Storing the session ID in the cookie is more secure but requires the client browser to support cookies.
From https://learn.microsoft.com/en-us/dotnet/api/system.web.configuration.sessionstatesection.cookieless?view=netframework-4.8

Related

Is there any way to create ip-independent http session?

I have seen some sites, where your authentication does note expire after your ip changes. How to create such session, and how safe is it?
So, how does session validate then? by some hardware information?
The fact that you have a session cookie is the validation.
Sessions work by creating a server-side resource with a random id. For example, a random id is created, iuwehrc3948hg3w09x4h, and an entry in a database is saved with it. That random id is sent as a cookie to the browser. The browser returns this cookie with every request, the server looks up the database entry with this id and gets the associated session data.
The "validation" is that the browser possesses a valid session id. The browser can only know this id if it was given to it by the server previously. Because the id is entirely random, it should practically be unguessable by any 3rd party.
Having said this, cookie hijacking is a concern, in which a 3rd party outright steals a valid session cookie (e.g. through a shared network, malware installed on the victim's machine etc.). In this case recording the IP address of the client in the session and validating it as well can help mitigate problems; but as you note, it also means that sessions have an extremely limited life span. The most practical solution to avoid session hijacking is to use HTTPS throughout.

ASP.NET session vs session state and cookies vs cookie less

Please help me whether my understanding is right.
ASP.NET sessions are stored on the web server and no cookies whatsoever are used for this.
ASP.NET if configured to use session with webconfig->session state: then we can configure it as either stateconnection or as sqlconnection.
ASP.NET if configured to use session state (either as stateconnection or as sqlconnection) then when user uses sessions in code then the cookies on client machine are used unless you specify in webconfig that cookieless=true
If we use <sessionState cookieless="true" /> then by default the stateconnection is set to localhost
When talking about Session in many dynamic web sites you want to store user data between HTTP requests (because http is stateless and you can't otherwise associate a request to any other request), but you don't want that data to be readable / editable at client side because you don't want the client to play around with that data without passing through your (server side) code.
The solution is to store that data server side, give it an "id", and let the client only know (and pass back at every http request) that id. There you go, sessions implemented. Or you can use the client as a convenient remote storage, but you would encrypt the data and keep the secret server-side.
Of course there are other aspects to consider, like you don't want people to hijack other's sessions, you want sessions to not last forever but to expire, and so on.
Session State contains information that is pertaining to a specific session (by a particular client/browser/machine) with the server. It's a way to track what the user is doing on the site.. across multiple pages...amid the statelessness of the Web. e.g. the contents of a particular user's shopping cart is session data. Cookies can be used for session state.
Cookies are small pieces of text, stored on the client's computer to be used only by the website setting the cookies. This allows webapplications to save information for the user, and then re-use it on each page if needed.
Every session will have SessionID. And Session ID is a unique number, server assigns to a specific user, during his visit(session). And defaultely, session ID is attached to a cookie and this cookie will be shared from client to server (and server to client) during its requests/responses. And server will identify session based on session id which is retrieved from cookie.
And regarding cookieless, if your browser doesnt support cookie or disabled, then cookieless will be used. Since it is Cookieless, asp.net can not create a cookie to save session id. Instead, the session id will be passed in query string.
Session : stored on server (memory or DB) and all pages in web application can use data in it.
Session State : store and retrieve values for a user as the user navigates pages in a web application.
Cookies : stored on client side as a file containing non sensitive data, but data like user favorites and preferences.
Cookieless : pass session id in URL query string and not storing it in cookies, in case you expect user to prevent or delete cookies.

Is session stored in client side or server side

I was wondering if HttpContext.Session uses cookies to store data. A work colleague told me that in a mobi site, phones generally do not have cookies and therefore you don't have session. I always thought session is data that is stored on the server side and is not dependant on client side objects please explain if I am wrong.
I read this.
In ASP.NET; you have a Session cookie. This cookie is used to identify which session is yours; but doesn't actually contain the session information.
By default, ASP.NET will store session information in memory inside of the worker process (InProc), typically w3wp.exe. There are other modes for storing session, such as Out of Proc and a SQL Server.
ASP.NET by default uses a cookie; but can be configured to be "cookieless" if you really need it; which instead stores your Session ID in the URL itself. This typically has several disadvantages; such as maintence of links become difficult, people bookmarking URLs with expired session IDs (so you need to handle expired session IDs, etc). Most modern phones, even non-smart phones, support cookies. Older phones may not. Whether you need to support cookieless sessions is up to you.
If your URL looked like this:
http://www.example.com/page.aspx
A cookieless URL would look like this:
http://www.example.com/(S(lit3py55t21z5v55vlm25s55))/page.aspx
Where lit3py55t21z5v55vlm25s55 is a session ID.
You can learn more about ASP.NET's session state here
The session data is stored on the server, but it also stores an id string in a cookie to identify the user.
If cookies are not supported, the id string can't be stored, and the server can't pair the session when the user makes another request.
The session id is just a number generated by the server (either from a counter or randomly), so it doesn't contain any information from the data that you store in the session object.
(The application can also be configured to put the session in the URL instead of in a cookie. This enables you to use sessions without cookies, but it ruins your nice URLs.)
Nowadays it can be both.
Server Session
Server Side session already explained in the others posts. The session is stored on the server but it need a cookie to store an indicator of who is requesting the session value.
Client Session
The new concept of WebStorage defined by W3C shows how a client side session is nowasays needed.
Here is the HTML5 implementation of a WebStorage:
https://code.google.com/p/sessionstorage/
This is a tricky question in some ways, as it is a bit of both.
The session state, itself, is stored on the server. But, you need some type of indicator on the client to use it. Normally, this is a server cookie, which is very thin and is basically a GUID for the session and nothing more. But, you can set up sites to pass the session ID in the URI, so it need not be a cookie.
Not sure how phones deal with the session cookie concept, but since I can log in, and do not see IDs in URIs, I assume there is a mechanism, even if it does not handle user cookies.
Session id is by defauld stored as cookie. You can also configure your session to pass its id as a query parameter ("cookieless").

What is the lifetime for a session cookie?

I say until you log out, session times out or you close the browser. But am I right?
I had an interview today and the interviewer wanted to know if I log into a page and closes the browser (without logging off), what happens to the session.
I said that the session will be orphaned. He says no - because their users are able to connect back to the session by just opening up the browser (using a cookie only). I told him that's a persistent cookie - not a session cookie.
And I said that if that's the cause, there is nothing preventing the user from exporting the [persistent] cookie to a another computer and starting the session on that computer.
At first he said you can't export a cookie but when I explained how, he said that he'll look but since many many people including 2 architects came up with the design, it is unlikely they are all wrong.
A session cookie is a cookie without an expiration time.
Handling of session cookies varies by browser and by browser version, but generally cookies that have no expiration date are deleted when the last instance of that browser is closed (lifetime=runtime of the browser).
Importantly, the server-side session that corresponds to the cookie value has a completely independent lifetime that is defined on the server. HTTP is a connectionless protocol, so when your browser isn't in the middle of a transaction, the server side has no idea whether you're still there or not. Tomcat issues unique, fixed-length cookies named JSESSIONID that they link to stored session data on the server. In that case the session expiration time is stored on the server. ASP base64 encodes all the session info, encrypts it, and writes it to giant cookies in your browser so it doesn't have to store that session data on the server. The session expiration time is saved inside the encrypted data stored in the cookie. Either way there's a record of when the session should expire, so session lifetime can't exceed the server side timeout.
You can set the same cookies in another browser and send the same data (mostly cookies) that the first browser would have sent, and as long as the server timeout hasn't been reached, the server will let you access the server-side session the same way. When people do this to your cookies, it's called a session hijack.
Here's JavaScript code adding a "session" cookie, which is just a cookie where no "Expires" value has been set.
document.cookie="COOKIENAME=cookievalue";
Here's JavaScript that adds a cookie with a specific expiration time, meaning that the browser is instructed to stop sending it with outgoing requests after that time:
document.cookie="COOKIENAME=cookievalue; expires=Fri, 31 Dec 9999 00:00:01 GMT";
The cookie data sent to the server does not include metadata like expiration time; the server only sees the key=value pairs.
Expiration data is only for the browser to read.
Setting a cookie with either of the above methods will cause the browser to send that cookie to the server this way:
Cookie: COOKIENAME=cookievalue
The server initially sets the cookie with or without an expiration date, but it has no idea whether that has been changed, and it doesn't really care. There's no functional difference between a cookie set to expire next month and a session cookie on a computer that stays on with the browser running until next month.
You are absolutely right. Session cookies are deleted when the browser closes and persistent cookies are deleted when their expiration time is up. Their website must use persistent cookies if the sessions stays alive after the browser closes. All cookies can be exported to another computer. This is a well known security vulnerability that is mitigated by using SSL.
There isn't a clear definition of "session" in web applications. A web site may decide to use either persistent cookies or session cookies to look up a session context on subsequent requests (or maybe something besides cookies). If the session lookup is done through a session cookie, then what you said about the session being orphaned (on the server, not accessible by a client) is correct.
However, "when you close the browser" is ambiguous. If you have two instances of Internet Explorer open, for example, both windows may be keeping a session cookie alive. Therefore, closing "the browser" that the web site page is displayed in won't necessarily clear the cookie.
Not sure if it's the same as ASP, but I know that in PHP it's 20 minutes

Cache VS Session VS cookies?

What are the do's and don'ts about Cache VS Session VS Cookies?
For example:
I'm using Session variables a lot and sometimes have problems in a booking-application when users start to order products and then go to lunch and come back some hours later and continue the booking. I store the booking in the session until the user confirms or aborts the booking so I don't need to talk to the database and handle halfway bookings in the database when users just click the X in the browser and never comes back.
Should I instead use cache or cookies or some combination for this?
(Also when there is some error in the app, the session-object resets itself and I get more problems because of that)
I'm mostly doing desktop-programming and feel I lack lots of knowledge here so anyone who can expand on where to use Cache, Session, Cookies (or db) would be appreciated
Edit: From the answers it seems that a combination of DB and cookies is what I want.
I have to store the booking in the database connected to a session-id
Store the session-id in a cookie (encrypted).
Every page load checking the cookie and fetch the booking from the database
I have a clean-up procedure that runs once a week that clears unfinished bookings.
I can't store the booking as a cookie because then the user can change prices and other sensitive data and I had to validate everything (can't trust the data).
Have I got it right?
And thanks for great explanations to all of you!
State management is a critical thing to master when coming to Web world from a desktop application perspective.
Session is used to store per-user information for the current Web session on the server. It supports using a database server as the back-end store.
Cookie should be used to store per-user information for the current Web session or persistent information on the client, therefore client has control over the contents of a cookie.
Cache object is shared between users in a single application. Its primary purpose is to cache data from a data store and should not be used as a primary storage. It supports automatic invalidation features.
Application object is shared between users to store application-wide state and should be used accordingly.
If your application is used by a number of unauthenticated users, I suggest you store the data in a cookie. If it requires authentication, you can either store the data in the DB manually or use ASP.NET profile management features.
Web is by nature disconnected model and none of the options mentioned (Session, Application, Cache, ...) are reliable enough. Session will timeout, worker process recycles, etc.
If you really need to store the users progress, reliably and through extended periods, the database is your only solution. If you have users profile (if the user must log in), then it's straightforward. If not, generate a unique Id, store it in the cookie (or URL) and track the user based on that identification.
Just make sure the Id is encrypted and then base64 encoded string and not just a numeric value.
EDIT:
After your additional explanation in the original question and comment from Mehrdad Afshari, good solution for you would be to use Session but set the storage to Sql Server instead of InProc.
Here's more details and instructions how to set it up: http://msdn.microsoft.com/en-us/library/ms178586.aspx
Have in mind that you will STILL have the session timeouts, but they will survive application pool recycles, even server restarts.
If you truly need a permanent storage, custom solution with the database, as I originally outlined is the only solution.
Session is stored on the server will time out by default in 20 minutes (This is adjustable). I would store this in a cookie, or in viewstate(if available) to prevent the timeout.
If your state is stored InProc(the default setup), then having more than one server in a farm is going to cause you issues also unless you have implemented some sort of "sticky session" that will keep the user on the same server in the farm for subsequent calls.
I try to avoid session when possible(puts extra load and memory usage on the server), and keep viewstate turned off when possible to keep the page size low. Cookies are often the most lightweight option, but your users might have this turned off and you will need a fallback mode that still allows them to use the site.
Edit (adding clarification based on response from asker):
Viewstate is stored in a hidden field, and is a serialized representation of all objects in Viewstate storage. Viewstate is automatically used to store the page's state, but you can explicitly add and retrieve your own objects to and from Viewstate programatically if you choose to.
So yes, datasets can be stored in Viewstate.
First thing you must know! cookies are used by session! The server knows who is your user thanks to the cookie which is exchanged between the client and server every request (this works with HTTP headers set-cookie and cookie).
The real question is:
If you want to store user information during the navigation, then you should use session.
If your client doesn't support cookies, then you can decide to store a cookie inside each request, encoded in the URL (the server will use the URL instead of the cookie to find the right session for the request).
Then consider where you want to store your session:If your site must have high disponibility and high performance, then you must not store session inside the process but inside a database. This way you will be able to share the work among several web server.
But you will loose in simplicity (because objects you store in your session must be serializable), and you have one more round trip between your webserver and your database server.
I was always confused between LocalStorage, SessionStorage and Cookie, but not anymore.
Just link the words are self explainable what they suppose to do.
LocalStorage: Local Storage, what does that mean, just thing you don't know anything about technology, but by the itself you can guess.
It is some storage which stores data locally.
that what it is.
IT stores data in Browser without any expiration until user clear it through JavaScript code or Clear browser cache.
Session Storage: It seems like it also stores data but related to a session then how different it is from localStorage?
The main difference is your session storage data will be deleted once the session is finish or browser tab is closed or the browser is closed.
You can just try in browser console by setting
localStorage.setItem('name' , 'alex')
sessionStorage.setItem('session','seesion value')
and then close tab and open again, you can still find localStorage data but not sessionStorage data.
Cookie: So this is totally different from the above two.
A cookie generally used for the server-side purpose.
Stores data that has to be sent back to the server with subsequent
requests.
Its expiration varies based on the type and the expiration
duration can be set from either server-side or client-side (normally
from server-side).
Cookies are primarily for server-side reading (can
also be read on client-side), localStorage and sessionStorage can
only be read on client-side.
Size must be less than 4KB.
Cookies can
be made secure by setting the httpOnly flag as true for that cookie.
This prevents client-side access to that cookie
You should not use the Cache-object to cache session data, for the cache is shared between all users. Instead you could use Asp.Net Profile properties to store your data or you could add an event handler to the Session_End event and store the data if the user leaves the computer for too long.
Cookie is a piece of information shared between co-operating pieces of software, by storing client-specific information on the client's machine and later retrieved to obtain the state information.
chose the term "cookie" as "a cookie is a well-known computer science term that is used when describing an opaque piece of data held by an intermediary". The term opaque here implies that the content is of interest and relevance only to the server and not the client. The browser will automatically include the cookie in all its subsequent requests to the originating host of the cookie. A cookie has a name and a value, and other attribute such as domain and path, expiration date, version number, and comments. for more
Cookie Version:
Cookie: cookie-name=cookie-value; Comment=text; Domain=domain-name; Path=path-name; Max-Age=seconds; Version=1; Secure
Server-side session data can store large data and a client-side cookie data are limited in size sent from a website to server, cookies usually contains reference code by this saving data transfer size. Session closes as soon as browser closed, but cookies are exist longer. Browser sends a session ID to the server as a URL param, cookie, or even HTTP headers.
Cache is a hardware or software component that stores data so future requests for that data can be served faster; the data stored in a cache might be the result of an earlier computation, or the duplicate of data stored elsewhere.
Cookies are stored in browser as a text file format.It is stored limit amount of data.It is only allowing 4kb[4096bytes].It is not holding the multiple variable in cookies.
we can accessing the cookies values in easily.So it is less secure.The setcookie() function must appear BEFORE the tag.
Sessions are stored in server side.It is stored unlimit amount of data.It is holding the multiple variable in sessions. we cannot accessing the cookies values in easily.So it is more secure.

Resources