ASP Server reduce session timeout - asp.net

I'm running a website on a shared ASP.NET 4.0 server.Therefore I only have limited memory size to store my users' session state.
The program I've written doesn't use Session variables: once a page is ready it is sent to the user and voilĂ . The rest is JavaScript and when the user click a link, I don't care if a new session is to be opened.
The question is: what if I reduce the session timeout to say 1 muinute only?
Will the user suffer from extra delays?
What if I go sessionless?
Since I do not use login-password for the users, I'm suspecting it won't impact the performances. Am I right?
Is there any cave at?.
Thanks.

Sessions are only needed if you need to store some "state" - to "remember" or "know" something about a specific client (user/browser) on the server-side (you can use cookies on the client side).
If you have no need to do so, you can turn off sesssions..
For MVC (note the comment by Brad Wilson for MVC2)

Related

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.

Requirements for modal authentication (as a Login page iFrame or object) without getting redirected to Login page?

There might be a few questions here, but one major question... what should be implemented if we make a modal authentication work? Let me try to explain..
Current environment:
ASP.NET w/ .NET 4.0 w/ forms authentication
Our customers that use our lab software have to be extra cautious of another user taking control of their computer, so we can't implement persistent timeouts (I think the last time I read, you can keep extending the timeout as long as there's something happening in ASP.NET, right?). Even though we have password authentication throughout our laboratory rich client application, we still don't want a random person walking by some employees desk to see what they're working on and have something get compromised. So I've been thinking about this for quite some time and tonight I had an epiphany. What if we were to have the Login page pop up in a modal dialog within an iframe (or object tag) in a modal div that's inside of our masterpage? How can we keep their session from ever expiring, but require them to login after the session has timed out? Is there anything else you can think of that will be required if we were to implement something like this for it to work? Note, we have session variables within the software that cannot be reset if this occurs. How can we keep them persistent but still make this work? The main thing is I want to avoid having them be redirected to the Login page. This is rather annoying for end-users. By law, they need to have the timeout set to 2 minutes, so I thought this would be really cool if I can make it work. Any other things we need to watch out for??
I can't but think that it's scary to use asp.net session, especially with forms-auth - because, the user gets 2 cookies: session and auth. Imagine what would happen if, somehow, authenticated user A would steal session cookie from authenticated user B: it would result in user A having access to all data that user B owns (unless your code checks whether user-id from auth-cookie owns the session object. In other words, I would suggest to get rid of the session, or at least add user-id value to session object and make sure you check that user id from the auth-cookie matches that within application_authorize event, maybe. You didn't ask for this info, but I think it's appropriate, regardless.
Since the session and the auth cookies have little to do with each other, as far as browser is concerned, and your goal is to keep the session alive, while auth-cookie should expire, then, you can maybe solve that by writing a piece of JS (hint: window.setInterval) that regularly pings some ANONYMOUS url (aspx page) at your server (make sure you add a random query to those requests; e.g. new Date().getTime()). The anon aspx page would need to read (do not write!) some value from the session (or simply retrieve the session object) - just to keep it alive (maybe this isn't really necessary; do experiment), but the browser WILL be sending asp.net session cookie with these requests, so you can keep the session object alive forever this way.
On the other side, your auth-cookie will expire. However you MUST set web.config settings (authentication > forms) to NOT use sliding expiration (as that mode essentially extends the validity/expiration of the auth cookie for another whatever-the-timeout-is minutes). Then, you can be sure that, after the cookie expires (e.g. after 20 min), when the user clicks on a protected link (well, a link that links to protected page; non-anon page), then they will land on login page. I know that you don't want this. So, to solve that, add another (independent) piece of javascript (hint: window.setTimeout([code], 2 * 60 * 1000) // to fire after 2 min since the page-load) to launch the login dialog. The login dialog would extend the auth-cookie by posting the uid/pwd and letting asp.net validate it.
Another thing: if you have ajax going on on that page, you must think of resetting these js timeouts back to 0 (or cancelling then reinitializing interval and timeout events). In other words, you can't start measuring inactivity since the page load - you have to reset the inactivity counter on every user's action (click; or at least on every ajax callback).
What I'm suggesting here may be an overkill. I would probably try to solve this differently. I would try to eliminate in-process session from the picture, and reload it based on auth-cookie's user-id from whereever user data is, every time it's needed (or once per request). I don't know why it's so important to keep the session object hanging in memory, even when the user is logged out (how do you know they won't leave for a week; keeping sessions alive would be killing your server if you had a large number of users). Maybe store the session data in database or some other caching mechanism on the network (e.g. memcached) and retrieve it once per request (e.g. in application_authorize), store it in request.context (to eliminate retrieving it multiple times from multiple places). Then, your auth-cookie will expire, and use JS to popup the login dialog a few min before the auth cookie expired (to avoid the gap where the user will land on login page if they click on a link, if you care about that even).
I hope these ideas help.

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.

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();

How do I explicitly set asp.net sessions to ONLY expire on closing the browser or explicit logou?

By default the session expiry seems to be 20 minutes.
Update: I do not want the session to expire until the browser is closed.
Update2: This is my scenario. User logs into site. Plays around the site. Leaves computer to go for a shower (>20 mins ;)). Comes back to computer and should be able to play around. He closes browser, which deletes session cookie. The next time he comes to the site from a new browser instance, he would need to login again.
In PHP I can set session.cookie_lifetime in php.ini to zero to achieve this.
If you want to extend the session beyond 20 minutes, you change the default using the IIS admin or you can set it in the web.config file. For example, to set the timeout to 60 minutes in web.config:
<configuration>
<system.web>
<sessionState timeout="60" />
... other elements omitted ...
</system.web>
... other elements omitted ....
</configuration>
You can do the same for a particular user in code with:
Session.Timeout = 60
Whichever method you choose, you can change the timeout to whatever value you think is reasonable to allow your users to do other things and still maintain their session.
There are downsides of course: for the user, there is the possible security issue of leaving their browser unattended and having it still logged in when someone else starts to use it. For you there is the issue of memory usage on the server - the longer sessions last, the more memory you'll be using at any one time. Whether or not that matters depends on the load on your server.
If you don't want to guesstimate a reasonable extended timeout, you'll need to use one of the other techniques already suggested, requiring some JavaScript running in the browser to ping the server periodically and/or abandon the session when a page is unloaded (provided the user isn't going to another page on your site, of course).
You could set a short session timeout (eg 5 mins) and then get the page to poll the server periodically, either by using Javascript to fire an XmlHttpRequest every 2 minutes, or by having a hidden iframe which points to a page which refreshes itself every 2 minutes.
Once the browser closes, the session would timeout pretty quickly afterwards as there would be nothing to keep it alive.
This is not a new problem, there are several scenarios that must be handled if you want to catch all the ways a session can end, here are general examples of some of them:
The browser instance or tab is closed.
User navigates away from your website using the same browser instance or tab.
The users loses their connection to the internet (this could include power loss to user's computer or any other means).
User walks away from the computer (or in some other way stops interacting with your site).
The server loses power/reboots.
The first two items must be handled by the client sending information to the server, generally you would use javascript to navigate to a logout page that quickly expires the session.
The third and fourth items are normally handled by setting the session state timeout (it can be any amount of time). The amount of time you use is based on finding a value that allows the users to use your site without overwhelming the server. A very rough rule of thumb could be 30 minutes plus or minus 10 minutes. However the appropriate value would probably have to be the subject of another post.
The fifth item is handled based on how you are storing your sessions. Sessions stored in-state will not survive a reboot since they are in the computer's ram. Sessions stored in a db or cookie would survive the reboot. You could handle this as you see fit.
In my limited experience when this issue has come up before, it's been determined that just setting the session timeout to an acceptable value is all that's needed. However it can be done.
This is default. When you have a session, it stores the session in a "Session Cookie", which is automatically deleted when the browser is closed.
If you want to have the session between 2 browser session, you have to set the Cookie.Expired to a date in the feature.
Because the session you talk about is stored by the server, and not the client you can't do what you want.
But consider not using ASP.NET server side session, and instead only rely on cookies.
Unfortunately due to the explicit nature of the web and the fact there is no permanent link between a website server and a users browser it is impossible to tell when a user has closed their browser. There are events and JavaScript which you can implement (e.g. onunload) which you can use to place calls back to the server which in turn could 'kill' a session - Session.Abandon();
You can set the timeout length of a session within the web.config, remember this timeout is based on the time since the last call to the server was placed by the users browser.
Browser timedout did not added.
There's no way to explicitly clear the session if you don't communicate in some way between the client and the server at the point of window closing, so I would expect sending a special URI request to clear the session at the point of receiving a window close message.
My Javascript is not good enough to give you the actual instructions to do that; sorry :(
You cant, as you can't control how the html client response.
Actually why you need to do so? As long as no one can pick up the session to use again, it would expire after that 20 minutes. If resources does matter, set a more aggressive session expiry (most hosting companies did that, which is horribly annoying) or use less objects in session. Try to avoid any kind of object, instead just store the keys for retrieving them, that is a very important design as it helps you to scale your session to a state server when you get big.
Correct me if I am misreading the intent of your question, but the underlying question seems to be less about how to force the session to end when a user closes the browser and more about how to prevent a session from ending until the browser is closed.
I think the real answer to this is to re-evaluate what you are using sessions to do. If you are using them to maintain state, I agree with the other responses that you may be out of luck.
However, a preferred approach is to use a persistent state mechanism with the same scope as the browser session such as a cookie that expires when the browser is closed. That cookie could contain just enough information to re-initiate the session on the server if it has expired since the last request. Combined with a relatively short (5-10 min) session timeout, I think this gives you the best balance between server resource usage and not making the user continually "re-boot" the site.
Oh you have rewritten the question.
That one is absolutely feasible, as long as javascript is alive. Use any timed ajax will do. Check with prototype library http://www.prototypejs.org PeriodicalExecutor or jQuery with the ajax + timer plugin. Setup a dummy page which your executor will call from time to time, so your session is always alive unless if he logouts (kill the ajax timer in the same time) or close browser (which means the executor is killed anyway)

Resources