Does an ASP.NET website use cookies by default? - asp.net

It seems like there are a lot of ways but no default. For State management, does ASP.NET use cookies by default?
If so, what are the alternatives to using cookies?
If not, what does ASP.NET use by default to manage state?

Yes - by default, ASP.NET uses cookies to maintain session.
That is, a unique "Session Identifier" cookie is stored on the client to keep track of sessions on the server (state service, sql db, etc).
But in the web.config, you can set cookieless to true:
<sessionState mode="InProc" cookieless="true" timeout="20" />
This will cause that very same "Session Identifier" to be stuck in the URL, and no cookies will be used.
Don't get confused though - the cookies dont store the actual "session". It sounds like you think cookies can be used as an alternative to something like the ASP.NET state service.
When in fact, the cookie just stores an identifer in order to "track" the session, in other words - this "identifier" is passed between the client-server on every HTTP request, this way the server can synchronize a particular session item with the client it belongs to.
Cookie-based/Cookieless session is irrespectible of what actual state storage mechanism you have in place - whether it be In Process session, ASP.NET State Service or SQL Server. It simply dictates the way in which the server is allowed to keep track of sessions.
Of course, cookieless sessions will suit clients that are likely to turn cookies off, but the disadvantage of this is you have ugly URL's, but this can be negated quite easily with the use of URL rewriting, although i would recommend against this - many have reported problems in attempting to do so.
HTH

Related

One server cooklieless true or false

I've looked at questions such as Set Sessionstate cookieless="true" in asp .Net, is the sessions state maintained? and Which one is better, InProc or SQL Server, for Session State mode in asp.net? but wondered if there an advantage or disadvantage to cookieless in true vs. false mode assuming everything is on one server.
We're looking to have around 200 people a day register and login, mainly text with some small PDF uploads (2Mb at most and say 5 documents).
Is there any upside to show set Cookieless to True in this or any instant (again assuming one server)
No, there isn't, not for that small amount of users anyway, unless they are using clients that does not allow or support client side cookies.
If you choose cookie based sessions, the InProc is fast, StateServer slow (but works for a server farm (multiple servers)):
Have a look at these post as well, especially the first one
https://security.stackexchange.com/questions/17719/what-risks-do-cookieless-sessions-have-what-are-the-mitigations/17733
ASP.NET session vs session state and cookies vs cookie less
What are cookieless sessions?
StateServer mode is best.
It will not lost session variable values.
Also cookieless=true session is best, because coockieless=false will generate sessionstring in url path.
Any one can copy that url path to access website from other computer.

Cache contains different data for subdomains

I'd like to ask about strange behavior of Cache object. I use Cache to store data specific for user (more accurately for session) with SessionID as a key.
For some reason the data in Cache appears not to be the same for different subdomains. I managed to keep SessionID equal across all subdomains:
- I set domain attribute in httpCookies element in web config like ".domain.com".
- I used this trick to ensure that SessionID cookie is stored across all subdomains.
- I set sessionState mode to SQLServer.
I ensured that SessionID is really the same for all subdomains. What's more, it is interesting that when I use session state in place of cache, everything works just fine. Session returns expected data for all subdomains. But when I use cache with SessionID as a key, cache returns different data for different subdomain.
Of course, I could keep it in session state but I'm not really fan of it and try to avoid it whenever I can.
Any ideas would be appreciated.
What's more, it is interesting that when I use session state in place
of cache, everything works just fine.
It works because you store SessionState in centralized location which is SQLServer.
The Cache for the current application domain..
If you want to have same cache for all app domains, you need distributed caching such as Windows Server AppFabric

Alternative to Session for a per-user variable in ASP.NET MVC

I am working on a MVC 3 application that will be hosted in a web-farm with a multi-worker process setup. There are about a dozen variables that are being stored in Session but are getting lost due to the IIS setup.
By getting lost I mean that when the Logon process succeeds I see through logging that I have set the Session variables but then after the Redirect action and on the landing Controller Action the Session variables are often empty. I'm not sure if this is related but this is in a HTTPS.
We are looking at the possibility of moving our user-specific settings that are stored in Session out to some other mechanism but there is one variable that I won't be able to do that with. Given the above deployment environment I have the following questions.
Are cookies my only (best?) alternative to storing Session variables for user-specific settings?
If so is there a secure mechanism for writing cookies so they cannot be manipulated and can still be read in a multi-server environment?
As I understand it System.Runtime.Caching suffers from the same problem when ran in the above IIS configuration. Is that true?
Are cookies my only (best?) alternative to storing Session variables
for user-specific settings?
No - they are about the worst possible approach. Three reasons that come to mind:
They can be manipulated.
They travel with every request from client to server - inefficient.
They will add more complications to your implementation since you'll have to start thinking about securing them in different ways.
If so is there a secure mechanism for writing cookies so they cannot
be manipulated and can still be read in a multi-server environment?
See answer above.
As I understand it System.Runtime.Caching suffers from the same
problem when ran in the above IIS configuration. Is that true?
True. You should be using any of the State Providers that are out of proc. You can either use Sql Server to store session data -provided your objects are serializable, obviously- or the State server mode mode="stateserver"
Read here for more details

Retrieve SSL session id in asp.net

Is there any way to retrieve the SSL session Id serverside in asp.net?
the short answer is no. This is an intentional limitation of IIS, so as to prevent people from taking a dependency on something that isn't dependable.
Out on the market, you will find various hardware load-balancers that will offer features like server persistence based on SSL Session ID, but they don't work very well because SSL renegotiation can happen at any time. In Internet Explorer 8, for example, a new SSL session is negotiated for every tab that is opened to a web site. You can expect similar behaviour from other multi-process browsers. So, I must stress that you should not use SSL Session ID for any kind of user identification purposes.
That said -- If you really need the SSL Session ID information for some specialized task, I recommend using Apache, mod_ssl and mod_proxy as a front-end to your IIS system. With a bit of fiddling, you could coerce mod_ssl into giving you the session ID, which you could then add to a proxied request to your IIS server as a query string parameter.... or you could store it in a database.
Tim,
Are you really "just" trying to retrieve the Session ID string or do you maybe lose all session information when switching to SSL? this would be a quite common problem, because the session on serverside is lost when using "InProc" session storage, and the session cookie on the client might be lost when not stored in a common domain.
Therefore, you should switch to state server or sql server session management in Web.config file, for example:
<sessionState mode="SQLServer"
cookieless="true"
regenerateExpiredSessionId="true"
timeout="30"
sqlConnectionString="Data Source=MySqlServer;Integrated Security=SSPI;"
stateNetworkTimeout="30" />
Beside that, I don't really know why you shouldn't be able to retrieve HttpContext.Current.Session.SessionID also in SSL mode as well.
Some MSDN Links:
MSDN: HttpSessionState.SessionID Property
MSDN: ASP.NET Session State Overview
Maybe this helps somehow.
Best regards

asp.net: moving from session variables to cookies

My forms are losing session variables on shared hosting very quickly (webhost4life), and I think I want to replace them with cookies. Does the following look reasonable for tracking an ID from form to form:
if(Request.Cookies["currentForm"] == null)
return;
projectID = new Guid(Request.Cookies["currentForm"]["selectedProjectID"]);
Response.Cookies["currentForm"]["selectedProjectID"] = Request.Cookies["currentForm"]["selectedProjectID"];
Note that I am setting the Response cookie in all the forms after I read the Request cookie. Is this necessary? Do the Request cookies copy to the Response automatically?
I'm setting no properties on the cookies and create them this way:
Response.Cookies["currentForm"]["selectedProjectID"] = someGuid.ToString();
The intention is that these are temporary header cookies, not persisted on the client any longer than the browser session. I ask this since I don't often write websites.
Before changing any code, I would investigate why session variables are disappearing.
Perhaps it is as simple as changing the timeout setting in the web.config?
Here's a list of the session state settings in the config file: Session Element on MSDN
====================================================
Oh yeah, one other thing to try in relation to your comment:
If my memory serves me, we had some issues in the past when deploying to a web garden/farm where multiple web sites on the same server would "clash". To get round this we explicitly names the cookie as so:
<authentication mode="Forms" >
<forms loginUrl="your-login-page.aspx"
cookieless="AutoDetect"
name=".A-NAME-WHICH-IS-UNIQUE" />
</authentication>
Name: Optional attribute.
Specifies the HTTP cookie to use for authentication. If multiple applications are running on a single server and each application requires a unique cookie, you must configure the cookie name in each Web.config file for each application.
The default is ".ASPXAUTH".
From here link text
No you do not have to keep resetting the cookie in the response.
Once set that cookie will continue to be sent with each subsquent request.
However I agree with Dominic you should first determine the reason you are unable to maintain the session in the first place.
Some reasons are:-
The host is using a web garden or a load balancer that does not support session affiliation
There is an aggressive setting for session timeout on the host
The host has a problem and is recycling the application pool frequently
Your client has overly tight cookie settings and is rejecting all cookies (however that would mean your alternative solution wouldn't work either)
Application logic may be faulty causing Session.Abandon or Session.Clear when it ought not.
In answer to your question about copying the cookie from the request to the response, no this is not necessary.
When the cookie is created it can persist for as long as you require.
If it is just needed for the duration of the session then do not set anything against the Expires property. In this case the cookie will be held in the browser memory and served up with each request to you website until the browser is closed.
If it is to persist between sessions the set the appropriate DateTime value against the Expires property. In this case the cookie is written as a file on the client machine and continue to be served up with each request to your website until it's exiry date is reached or it is deleted.
Of course, be aware clients can disble cookies in their browser.
I do agree with previous answer, that you should investigate the sessions timing out first!
But regarding cookies:
Request cookies are the cookies sent from the client to the server and Response cookies are the ones sent from server, telling the client to save them locally and attach them to the next, and all upcoming until the cookie is outdated, requests to the server.
Cookies have a limit on size and because of their behavior will create an overhead on data sent between server and client on requests, and can of course also be disabled on client side as well.
I would suspect that the reason you might be loosing session variables is that your application is running in a web garden. This means two or more processes are running your application.
In your web.config there should be sessionState tag. If mode="InProc" then try setting mode="StateServer". This will cause all the processeses hosting your application to use the session state server to store the session state elements. Also check the timeout as was mentioned previously.
The research I've done into cookies suggests they would not be a desirable alternative to session variables. Browsers enforce arbitrary limits on the number of cookies that can exist at any one time as well as the number per site. They are also prone to being dropped randomly.
You can enable cookieless sessions. There are some potential issues but it might work for your site.
I was a webhost4life customer up until two months ago, the issue I was experiencing was the application pool being recycled frequently - probably because the host had some kind of problem. In the end I moved to a VPS and never looked back (not a webhost4life VPS either).
For Sharing hosting the best approach is to use SQL Session State.
It's a little bit slower but much more reliable.
I had the same problems back in the days and my Memory Sessions were always getting erased, this happends because someone on the same hosting environment didn't know how to accomplish stings and IIS just reset the Application Pool, or it could even do by Auto Refresh the AppPool from the Hosting point of View (so no website will hang).
Since I started to use SQL State ... I just must say WOW!
you have total control in everything, even set the timeout (Memory Sessions are set by the machine config and no matter what you set in code or web config you will never override that setting)
and you gain something new, if you change the code, you users will not need to left the website to re.login again as they will continue from their existing session.
Setting it up it's fairly easy and you have a ton of examples on how to accomplish such behavior.
no matter what you do, DO NOT GO to cookies as they are not reliable!
You might consider using this little library:
http://www.codeproject.com/KB/aspnet/Univar.aspx
It can automatically switch to the session whenever the cookie is unavailable. It also has a server side implementation of the cookie whereby all cookies are stored on the server and asp.net authentification can be used to identify the user.

Resources