How does ASP.NET (or any web framework) implement persistent session state? - asp.net

For various reasons I am fed up with ASP.NET session state and I'm trying to do it myself (separate question coming soon related to why I'm fed up and whether it's feasible to do it myself, but for now let's assume that it is).
Security concerns aside, it seems like tracking sessions involves little more than storing a cookie with a guid and associating that guid with a small "sessions" table in the database, which is keyed on the guid and contains a small number of fields to track timeout and to link to the primary key in the user's table, for those sessions that are linked to registered users.
But I'm stuck on a detail with the cookie, in the case the user's browser is not set to accept cookies. It seems to me that each time a user accesses any page that has session state enabled, ASP.NET must determine whether the browser supports cookies. If there already is a session cookie sent with the request, obviously it knows cookies are accepted.
If not, it seems like it needs to check, which as I understand it involves trying to write a cookie and redirecting to a page that tries to read the cookie. So it seems, when a user with cookies turned off visits several pages of a site, that ASP.NET
(a) has to do this round-trip test for every page the user visits, or
(b) has to assume the browser accepts cookies and create a record with a (provisional) session id for the user on each page -- and if session state is supposed to be persistent, it seems it has to write that initial session id to the database on each page.
But (a) sounds crazy and (b) sounds crazy also, since we would quickly accumulate session ids for all these single-page sessions. So I'm thinking there must be some other trick/heuristic that is used to know when to do the round-trip test and/or when to actually create a record for the session.
Am I wrong to be perplexed?
(To be clear, I'm not talking about implementing a custom storage solution within ASP.NET's pluggable session state system. I'm talking about skipping ASP.NET's session state system entirely. My question is a more detailed version of this one: Implementing own Session Management in ASP.NET.)

Session behaviour is set through the sessionState element in web.config. In the sessionState element the HttpCookieMode can be set to one of UseUri, UseCookies, AutoDetect, UseDeviceProfile.
UseUri and UseCookies tell ASP.NET explicitly how to handle storing the session identifier. If UseDeviceProfile is used then the behavior is determined by whether the user agent supports cookies (not whether they are enabled or not).
AutoDetect is the interesting case that you are interested in. How ASP.NET is handling the auto detection is explained in Understand How the ASP.NET Cookieless Feature Works. In that article you will see that they have 5 different checks they do. One of the checks is, as you mention, to set a cookie and do a redirect to see if the cookie exists. If the cookie exists, then the browser supports cookies and the sessionID cookie is set. However, this is not done on every request because another check they do before tring to redirect is is check to for the existence of any cookies. Since after the initial set-cookie and redirect the sessionID cookie will be set then the existence of the cookie lets ASP.NET know that cookies are supported and no further set-cookie and redirects are required.

Well, cookies are a standard mechanism of web authentication. Do you have any reason at all why you wouldn't want to use them? Are you sure you're not trying to invent a problem where there isn't any problem?
Most serious websites I know of require the browser to accept cookies in order for the user to be authenticated. It's safe to assume that every modern browser supports them.
There's an interesting article about cookieless ASP.NET that you should read.
EDIT:
#o.k.w: By default the session state is kept by ASP.NET in-process (read: in memory). Unless told explicitly by the configuration to store the session in the database (SQL Server is supported out-of-the-box), this won't result in a database hit. The stale session states will get purged from the in-process storage. Unfortunately, with default ASP.NET settings every cookieless request will result in a new session being created.
Here's a detailed comparison of available session storage options: http://msdn.microsoft.com/en-us/library/ms178586.aspx.

Related

How can I use ASP.NET MVC (or Core) to detect and redirect cookieless sessions?

I'm creating a website where security conscious (paranoid) people might block cookies, and even authentication cookies.
I'd like to detect this instance, and redirect to a FAQ/Help page that describes the corresponding risks with cookieless sessions.
You're mixing terminology, so it's a little unclear what you're talking about. Sessions are either cookieless or not. If you're using cookieless sessions in ASP.NET, then every session is cookieless. As a result, it's kind of pointless to warn a user about the inherent security risks in something they are forced to use. If you're not using cookieless sessions, then every session requires a cookie, and again there's no point in warning a user about something that doesn't even apply to them.
The only thing that would make sense here, is to require a session cookie (no cookieless sessions) and then notify users without cookies enabled that they will not be able to utilize portions of your site that require cookies (authenticated areas and other places where you might utilize the session). To do that, you can either use JavaScript to detect whether cookies are enabled via navigator.cookieEnabled or you can do it server-side via:
Set a cookie or simply save something to the session (which will require a cookie to be set)
Redirect
Check for the previously set cookie or session data
If it exists after the redirect, then cookies are enabled. If not, then they are disabled.

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").

Does using cookies pose a threat to application security in asp.net?

Does using cookies pose a threat to application security in asp.net ? Or do we only use as a medium of saving user stats and non-vital information ? Got a little details of using cookies in asp.net from my own blog
IMO cookie is one of the best choice for some situations. For instance, storing the user's selected language. Also you can cache some sensitive information in the cookie as users' roles as ASP.NET Roles manager. But you should encrypt it without doubt and also you should set HttpCookie.HttpOnly = true to prevent javascript from accessing to cookie. Don't worry about supporting cookie in different browsers, size is premier (Browsers support only 4096bytes per cookie). Cookie is bandwidth killer, cause sends and receives within each request and response. Thus, you should use it in avarage. You can check if the client browser supports cookie as follows.
if (Request.Browser.Cookies) { // The browser supports cookie }
To learn more information about cookies, visit here.
Using cookies doesn't pose any threat to an application. It is the way you use them and the information you store that could be problematic. For example, you have to avoid storing sensitive information in cookies. If used for authentication, they should always be transmitted over a secure channel.
It depends on how you use them. Cookies should be treated as un-trusted input at all times, because they can be faked, edited or deleted. I've seen applications where a cookie contains something like admin=true which is obviously a very bad thing to do. If you're just dropping some guid and using that to track someone, but not caring if your results are accurate then that's fine.
If you want to make sure the cookie is semi-valid then you must add something like an HMAC to the cookie itself, which is what ASP.NET does with the forms authentication cookie (and the ViewState field). Of course this doesn't stop the user deleting the cookie, or copying a valid one from another user.
As long as you don't store critical information in the cookie (like the user's password) you should be fine.
Be careful with scenarios like that :
You store the user's ID in a cookie
You test against this ID to see if he's logged in
The user changes the ID manually in the cookie (easy to do)
The user gets access to another account
My point is that you have to keep in mind that the user can access a cookie and change it, so don't store anything you wouldn't want him to see.
Last thing, cookies often have a limited size so be careful: don't store too many information. If you store too much stuff (like a large object), you might end up breaking things.

Where is session stored if cookie is disabled on client's machine? What is actually stored in session?

In config file I have the below settings
sessionState mode="InProc" cookieless="false"
Does this indicates that the sessionid is stroed in cookies? If yes then how is it picked and sent to the server and how is it verified across postbacks.
What will happen if cookies are disabled in my browser, will the session(sessionid and session variables) still be created?
Where(default path) are the cookies created and stored by default for sessions and can i change the path?
What format and kind of data is stored in cookies for session?
If i store a class object in session then what is actually stored in cookies?
Also if i use authentication mode as forms with cookies then what will happen if cookies are disabled in browser?
The session cookie is a special non-persistant cookie. It's only stored in memory, so in most cases even when cookies are disabled it still works fine.
It's also possible to enable something called cookieless sesssions where the sessionID is embedded in the URL, like this:
http://yourserver/folder/ (encrypted session ID here) /default.aspx
Here's a link to an MSDN article with more details: http://msdn.microsoft.com/en-us/library/aa479314.aspx
NOTE: It is possible to completely block the session cookie. For instance, in IE8, I just went into Tools > Internet Options > Privacy. When I cranked the slider up to 'High' or greater, my sites never got past the login screen because the session cookie was blocked - in fact, Josh Stodola said below that in this case the session would never even be created on the server.
However, understand that this type of behavior effectively breaks the Internet. So unless you're building a site targeted at conspiracy theorists, in my opinion (and the opinion of most of the largest sites in the world) there's no need to cater to the tiny percentage of users who don't play by the normal rules.
For them, the Internet just isn't going to work the way it's supposed to.
My guess is that each request by the client will be seen as a new session by the server.
If you happen to grab the request headers from your browser, you can see that a SessionID is part of the header. This is used by the server to determine which session belongs to which user.
Instead of session id being passed via cookie, it is typically passed as a query string in the URL, or as a custom HTTP header. With the scenario you described, however, your user will never obtain a session because you have cookieless set to false.
I have not implemented this personally. But it should be like:
As Cookiless=false in web.config file and browser has disabled cookies, when first request for the page comes, HTTP module will check for forms authentication cookie. Now it will be empty which send user to login page. Now when second request for any page on website will come it will again find forms authentication cookie empty and send user to login page. So for every request user needs to create new session.
No, If cookies are disable the session will not work.
if you want to use session when cookies disable then you can pass session thru URL.
It stores directly in the browser
There are two ways session state can store the unique ID that associates client with server session; by storing an HTTP cookie on the client or by encoding the session ID in the URL.
Session Mode="InProc" is a default mode which stores the session state information in web server. However when you say cookieless="false" you are saying to stored unique ID in cookie. This Id is created when session is created, so during postback ID is picked up from cookie. If cookie are disabled in browser,yes session still will be created and this id is passed along URL.
You can browse to cookies by going to browser settings->Privacy->Content Settings->All cookie and site data->Stored with site name
Probable you might find cookies in %userprofile%\AppData\Roaming\Microsoft\Windows\Cookies but might differ from operating system to system.
In cookies you usually store small piece of insensitive personal information. If you need to store sensitive data such as user name and password it is better to encrypt those data.
In cookie you usually store information about the users. For more details please visit URL
http://msdn.microsoft.com/en-us/library/system.web.configuration.sessionstatesection.cookieless(v=vs.110).aspx
http://msdn.microsoft.com/en-us/library/ff647070.aspx#pagexplained0002_cookielessforms

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