Using Cookies for Web Session State - What are the pitfalls? - asp.net

Using in-process session state is evil when it comes to scaling web applications (does not play well with clusters, bombs out when server recycles).
Assuming you just need to keep a small amount of information in the session state, what is the downside of using encrypted cookie items for this purpose rather than specific state servers/db’s?
Obviously using cookies will create a small amount of network overhead, and clearly you operate under the assumption that cookies are enabled on the client browser/mobile device.
What other pitfalls can you see with approach?
Is this a good option for simple, scalable and robust sessions?

This is an excellent approach for simple, scalable, and robust sessions.
Of course the quality of your crypto is important, and that is often something that often proves tricky to get right, but it's possible to do.
I disagree with some of the other posters:
Any replay attack that can be launched against an encrypted cookie value can be launched against a session key stored as a cookie. Use https if this matters.
Session data stored in a state server or database is also lost if the cookie is cleared; when the session key is lost the session can no longer be retrieved.

Another pitfall is that they can be stolen and replayed on your site.
BTW: Instead of storing some stuff in the cookie, you should also look at storing a key in the cookie and using something like memcached (memcached works across server farms).

Well usually a cookie is used for the session ID, so as long as the amount of information is small it would be a good option to store the information in the cookie, though you shouldn't store anything of value (like CC numbers, SSN, etc) should really be stored in a cookie, even if encrypted.
I'm no expert, but in my experience I've found the following to be true (at least using PHP, and ASP.Net).
Cookie
[pro] Scales well, since it's transmitted on every request
[pro] Cookie can be required to submit only through an SSL connection
[pro] Can be used cross-server technologies, and cross-server machines
[con] Data is transmitted on every request and response
[con] Needs to be enabled on browser
State Server / DB
[pro] Data stored only on server
[pro] Data persists even if user clears cookies
[pro] Can be used cross-server technologies
[con] requires an ID to be passed on request/response (thus requires cookies or appending to every URL)
[con] doesn't scale well in default modes, but if an entire machine(s) can be devoted specifically and exclusively to state then this isn't much of an issue. Plenty of other scaling techniques out there that can be followed for scalability.
[con] Requires a session ID variable passed through URL or Cookie or other means, to keep the user tied to the data.

Related

Disadvantage of using session[""] in asp.net

In my project I use session to store user information ( username, password, personal image, and gender ) to be used in all pages of my project. I also use two other session to store small strings. Is there any disadvantage of using session ? also is there any risk of using session to store user password ?
Some things to take into account:
Don't store passwords. You should hash the incoming password, validate against the hash in your DB, and not hold on to it afterwards.
You should try to avoid using a write-access Session throughout the application, since you'll end up forcing asp.net to serialize incoming requests from the same session. Use read-only Session to avoid that. This could become apparent if you initiate multiple ajax calls simultaneously. More info here: https://connect.microsoft.com/VisualStudio/feedback/details/610820/session-based-asp-net-requests-are-serialized-and-processed-in-a-seemingly-inverse-order
Storing too much data in the Session could cause scalability issues, since all that information is held in memory on the server. If you switch over to SQL storage for sessions (common in webfarm/cloud deployments), then if the session is large every request on the server will have that Session data going back and forth between the server and the DB.
Content that goes into the session should be Serializable, just in case you decide to move over to a different persistent storage (such as sql server)
Using Sessions to retain information may not go well with stateless REST/WebApi endpoints (if you need to create any in the future)
Excessive use of Session for storage could make unit testing slightly more difficult (you will have to mock the Session)
By "personal image" I assume you are storing a url or such, and not an actual binary image. Avoid storing binary content. Only return the binary image file when the browser requests it, and don't store it in memory, the browser can cache that content easily.
You might also find the references linked in this answer to be useful in providing additional information: https://stackoverflow.com/a/15878291/1373170
The main problem with using Session and any machine depending properties is the scalability of the web site, so if you wanted to deploy your web site to a farm of servers then you can see the problem with depending on a machine state property since the request may be processed on different machines.
Hope that helps.

what are the alternatives of SESSION VARIABLES? [duplicate]

This question already has answers here:
ASP.NET Masters: What are the advantages / disadvantages of using Session variables?
(8 answers)
Closed 9 years ago.
What are the limitations of the session variable in developing large web application.
Also what are the best alternatives of the session variables.
Please provide me the alternatives of SESSION VARIABLES
To understand the advantages of not using sessions, you have to understand how sessions work.
In the default setup,
sessions are identified by a cookie set in the user's browser and
the session data is stored in-memory on the webserver
When the user sends a request to the server, the session cookie is sent along. It contains an identifier which the server uses to locate that particular user's session data.
You can configure ASP.NET to
use query parameters instead of cookies to store the session identifier
store the session data in a database (having a central data store for session data is particularly important if you have multiple servers serving your site)
Now for the advantages of disabling session state:
ASP.NET makes access to the session data thread-safe by serialising requests. This means that, when session state is enabled, ASP.NET refuses to serve concurrent requests from the same user. This is particularly an issue when the user's browser makes a lot of ajax requests. This problem can be mitigated by marking session state read-only for requests where you don't need to update it.
When the request comes in, ASP.NET has to fetch the session data, and it has to write data back when the request ends. This may not be a big issue if session state is stored in-memory, but if data is stored in a central database, this can cause serious performance problems.
Needless to say, these issues are exacerbated by storing large amounts of data for a large number of users.
For more information see
ASP.NET Session State Overview
Fast, Scalable, and Secure Session State Management for Your Web Applications
(that last article is a bit dated, but still a good read).
Alternatives
If you can, avoid session state altogether.
If you absolutely must associate data with the user, use the mechanisms of HTTP and make the browser carry the data in a cookie or perhaps a query parameter (this is partly what the whole REST-movement is about).
Hope this helps.
It depends upon the business logic of your application in some cases session may be the best choice , however there are lot of alternatives ,Session should be used if you are having different data for each request to your application ,you can post your data in hidden fields with your forms , but again ur question is a little bit of the track, You have to analyze your requirement than according to it you have to decide whether to use sessions or some other alternate solution , If I have to store id's of users than definitely I will go for sessions cause it will be different for each users , I would not keep very big data in session like keeping a dataset in session which few developers do . Then also questions comes if ur using session where u want to keep it in process or in server , if ur saving session in server it is very costly but in ssome scenarios its very useful .
Pros and Cons of Session Variables See Here
Since data in session state is stored in server memory, it is not advisable to use session state when working with large sum of data. Session state variable stays in memory until you destroy it, so too many variables in the memory effect performance.
Session variables and cookies are synonymous. So if a user has set his browser not to accept any cookies, your Session variables won't work for that particular web surfer!
An instance of each session variable is created when a user visits the page, and these variables persist for 20 minutes AFTER the user leaves the page! (Actually, these variables persist until they "timeout". This timeout length is set by the web server administrator. I have seen sites that the variables will collapse in as little as 3 minutes, and others that persist for 10, and still others that persist for the default 20 minutes. ) So, if you put any large objects in the Session (such as ADO recordsets, connections, etc.), you are asking for serious trouble! As the number of visitors increase, your server will experience dramatic performance woes by placing large objects in the Session!

In a classic ASP application, is it better to use a session or cookie for cross-page data persistence?

I have inherited a fix on a classic ASP application where we want to store some user session-specific data to persist across page loads/their session, and need a bit of a refresher.
In the past I have simply used Session variables - ie. Session("SomeVar") = SomeVal.
In IIS on the production box, I noticed that ASP / Session Properties / Enable Session State = false. Setting this to True allowed me to successfully begin using session variables.
I don't want to consume any more resources than necessary on the server. In the past, I believe that I was under the delusional misconception that session variables in classic ASP were stored on the client side. Revisiting this now - the data is retained on the server side.
The string I am saving is a GUID, for roughly 3000 connected clients.
What kind of server impact am I looking at if I implement this, and would using client-side cookies be a better option?
Lets analyse this a bit, a GUID takes about 40 characters as a string hence in Unicode thats 80 bytes, lets call it 100 bytes. 100 * 3000 = 300KB. Can server spare 300K for this? I think the server already in trouble if the answer were no.
However there are other impacts to enable session state. When sessions are enabled ASP adds its own cookie to the client which in size terms is probably equivalent to the one you would need if you were storing your GUID as cookie instead of in the session. Its worth noting that this session ID stored in the cookie uses an algorithm which some say is more predictable (I haven't got any evidence of that myself). Hence if you are using the GUID as some form of authorization then storing the GUID as cookie directly may be better.
There is a further significant change that happens when Session state is enabled. ASP requests from a client must be processed serially, the server will not process multiple requests from the same client in parallel. This is because the Session object is single threaded and since each request from a client needs access to it the requests cannot be processed at the same time.
That last point could have significant impact on the existing behaviour and performance that a client sees especially if AJAX techniques, multiple IFrames or other techniques which result in simultaneous ASP requests being sent to the server are being used.
Hence for the requirement you have my choice would be to store the GUID in a cookie and leave session state turned off.
Multiple servers/server farm? If so you might run into trouble using Session if you load balancer is not set to be "sticky" and send you to the same server each time. Can me a real headache to debug so becareful.

When are cookies are preferable than sessions?

public class ServletDemo extends HttpServlet{
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException{
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
Cookie cookie = new Cookie("url","mkyong dot com");
cookie.setMaxAge(60*60); //1 hour
response.addCookie(cookie);
pw.println("Cookies created");
}
}
I am seeing Java Cookies concept .
There is a lot of stuff on cookies , use it when small data needs to be stored on client side.
But could you please tell me , when should we use Cookies exactly ??
And when cookies are preferable than sessions ??
This one part of a whole set of design decisions relating to where we need to keep state information when several computers are involved in a system.
When you say "session" I suspect that you mean the HttpSession that servlet containers will manage for you. It's actually quite likely that the HttpSession is actually maintained by using a cookie: the cookie just holds some kind of a key to a table of sessions.
This pattern of passing some kind of reduced amount of data back to the browser and having the server keep track of the main stuff is also pretty common. Sometimes folks use all three: cookie for, say, the small stuff, HttpSession as a convenient cache, and the database for stuff they really care about.
There's lots of factors to consider, here's a few:
How much data is it reasonable to send in a cookie, too much things are going to go slow.
How secure is this? Servers often assemble lots more data then the user entered in this session, how confident are we that something sensitive can't be hijacked or read if we send it back to the browser in a cookie?
How reliable is our choice of session mechanism? Lose the browser, lose that 5k holiday booking we were just about to buy? Lose the HttpSession on the server? Perhaps the same outcome? (Some app servers have session replication, but it's an overhead).
Personally, I find that usually the HttpSession API is so convenient that I never choose to use cookies. My rule of thumb is "if it's readily re-creatable keep it in the HttpSession, otherwise make sure it's persisted in a database, if necessary creating a database specifically for state management (and not forgetting the housekeeping of that database).
Examples of re-creatable things: Items retrieved from a database (we can always get them again), things that the user would not mind re-entering (say a few search criteria). Example of non-re-creatable: the 17 page completed insurance application form.
Cookies are less secure than sessions.
A session is fully-controlled by the server. In both cases the client needs to securely present authentic session data, but with cookies there are more opportunities to sneak a look at what's going on internally. The consequences of cookie theft are in general worse then the theft of an opaque session ID.
Cookies can be faster to develop with because the server doesn't have set up session databases and the like, but they're a lower-quality solution if you care about design.
To answer your specific question, cookies are preferable to sessions when cookies can do what you can't do with sessions. I see two reasons to use them:
when you need some information about the client, and this information must keep existing across multiple client sessions, even if the user closes his browser. For example, an automatic login uses cookies: at the first request of a client session, the cookie is sent, and the web site is thus able to identify the user.
when you need to share some information between information between several web applications, provided their are all served from the same domain. For example, single sign-on can use cookies. The first application authenticates the user and sets a token cookie, which is sent to the second application. the second application may then use this cookie to automatically authenticate the user.

Session State v ViewState

In our application, we have a "BasePage" that declares a number of properties to be used by more or less every page in the app.
Inside these properties, they write to ViewState. These are all typically an int or small string value, nothing huge. Typical use is call a web service and hold an id for use within the page, for example.
I've used viewstate since I'm wary of the loss of session variables should IIS recycle for example. Also, I figured, very small values would not add hugely to the page size.
Am I being overly paranoid about session though and would it have been a better option.
Our environment is a 2 server cluster with SSL termination on each server, sticky sessions maintained by the load balancer - so using In Proc is not a problem per say, I'm just very wary of it.
Never trust your user sent data.
Even all data you receive is not sensitive, if you send it to your user browser, you should to check it again before use it. Maybe most users are legitimate, but just one can break your application.
What are your options to store data?
Hidden field; can ve easily tampered at client side
Cookie; ancient method to keep user specific data, but very size limited.
ViewState; your data go to client and come back, using bandwidth and could be tampered.
Session, InProc; your never have problems, until a application pool get recycled
Session, State server; you keep your session data in another server process.
Session, database; can work with almost (if not all) load balance scenarios, as you dont need stick sessions, nor to worry with app pools recycling. All your data are belong to us your SQL Server.
Reading your scenario, you probably need to deal with out-of-process session storage.
I think it's best to avoid using Session state where possible, especially on a server cluster even if you are using sticky sessions. Sessions can expire, or disappear when IIS recycles (like you said).
I'd go with keeping the values in ViewState or a cookie.
If it is not sensitive data, I would also prefer to store it in the HTML rather than the session.

Resources