Finding time until timeout fires in asp.net - asp.net

First of all, let me ask this:
Let's say that a web application has its timeout set to 10 minutes. For some reason, the user is idle. If he/she returns and press any key or moves the mouse, it resets the timeout? Or it is based on the last time it went to the server?
And now the second question: is there a way to find the time until the user gets logged off due to innactivity?

From MSDN:
The Timeout property specifies the time-out period assigned to the
Session object for the application, in minutes. If the user does not
refresh or request a page within the time-out period, the session
ends.
So in answer to your question, the timeout is reset if the user sends a request to the server by either navigating to another page or refreshing the current page (or possibly by using some form of AJAX keep-alive method (See this question)).
This article on Code Project provides a pretty good overview of Sessions within ASP.net
For your second question, this gets a little complex as the session timeouts are managed by IIS so your page has no idea how much longer the session will be valid for. I have seen examples where another timer is placed with in the page itself and when this reaches a certain low value the user is warned that their session is about to expire. The page could then refresh (resetting the session timeout value in IIS) and the user wouldn't be logged out / lose their session.
However, this will require the session timeout value that is configured is kept in sync with the value configured in the JavaScript function.

Related

what will happen after browser closing

We know that when we closed the browser, session gets destroy.
Please help me with below query.
Lets say i have clicked on submit button on my registration page and internally it get called SQL store procedure, which takes more time to execute..
on same time if i closed the browse what will happen?
Does my sql connection still available ? if yes then after closing browser still my store procedure is in execute mode?
when exactly the session get destroy?
Would like to know more about this life cycle , Thanks
First have this in mind.
The session is connected with a cookie on the users browser.
The session have a time out.
If anything of this two gone, the session is gone, so let see them analytically.
Cookie
If the cookie is a session cookie (temporary), then is gone when the user close the browser, if its not temporary then is gone when it expires, or of course if the user clears it, or if the user is in private mode is not even saved.
So when the cookie that is connected with the session is gone, you lose the session
The session can be lost even if the browser is not been able to read the session cookie for other reasons.
Session Data on server
The session that is connected with the cookie, is a Dictionary of data that lives on server.
The session have a timeout, so if the user did not update the call to the server inside this time, the server kills the session data on server.
Also, note that the session can be served on the SQL Server, or in a service that runs on background and keeps that data in memory.
If you save the session data on the memory, then they can be lost even before the session times out, from IIS recycle, from the service itself that clears it for their reasons.
Server Side Time Out
If you call a long time function, and the users ends their connection, then the procedure will be continue to runs until either ends either gets a time out. This is not so safe if your process takes 10 minute to execute, you probably gets timeout and never ends correct, even if the user is still connected. If you talk for few seconds, then its relative ok, the procedure will executed even if the users close his browser side.
Check the time out of the page and the time out of the sql server side. If you end well with the user connected, you will end the same and if the user close their connection in the middle.
Have in mind that in a heavy multi user call situation you may have a problem from the session locks, read this q/a ASP.NET Server does not process pages asynchronously
So take care the procedure to not take more than few seconds.
Last words
The most "secure way" to not lost your session in a time period is to use well setup cookie, that is not temporary and keep their life for some months (google keeps their cookie for two years), and use SQL Server to saves your session data.
More details to read at:
ASP.NET State Management Recommendations
Session would not retain values and always return null
Keeping a related ASP.NET application's session alive from another ASP.NET application
ASP.NET Session State Overview

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.

Can Session_End fire on window close? (ASP.NET)

I am putting an "online" counter on a website, and I have run into these two contradicting sources.
This one (I am using this example code):
http://aspdotnetfaq.com/Faq/How-to-show-number-of-online-users-visitors-for-ASP-NET-website.aspx
...says that:
Also when user closes his browser or does not click on any links in
our website, session expires, and our "OnlineUsers" global variable
is decreased.
However, this one:
http://www.velocityreviews.com/forums/t383710-session-end-guarantee.html
...says that:
Closing the browser window, or browsing to another site will NOT cause
Session_End to fire, at least, not straightaway - the server has
absolutely no way of knowing what happens on the client machine until
it gets another HttpRequest from it. In this instance, Session_End
will fire when the session times out naturally.
I have tested and it seems that Session_End DOES NOT fire.
I basically want you guys to confirm or comment on this.
Is it possible to update the online counter on browser-close?
The second is true
Closing the browser window, or browsing to another site will NOT cause
Session_End to fire, at least, not straightaway - the server has
absolutely no way of knowing what happens on the client machine until
it gets another HttpRequest from it. In this instance, Session_End
will fire when the session times out naturally.
Session time out is 20 minutes by default. You can confirm this by not doing any activity on your website for 20 min.
Your two links are not contradictory. The first link is poorly worded, but it basically says what the second link says. It would be easier to understand if it were written like this:
Also when user closes his browser or does not click on any links in our website (after a period of time) the session will expire, and our "OnlineUsers" global variable is decreased.
Also note that Session_End may not always fire, especially if the session is killed or bounced (for example, if you update the web.config, the worker process recycles, or in some cases an uncaught exception occurs).
As is pointed out later in the first link posted the Session_End event fires after the session timeout expires. If the user who is associated with a session sends no requests to the server before the session timeout value expires the session_end event will be fired and the session will be removed from memory.
MSDN for asp.net session state: http://msdn.microsoft.com/en-us/library/ms178581.aspx

Where to set session timeout?

The application sets session.timeout in Application_AcquireRequestState event handler.
Before session expires, there is notification window popping up. It resets session timeout to, say, 3 minutes (normally, it is 30 minutes), through Application_AcquireRequestState.
The notification offers user an option to extend session for another 30 minutes. If user clicks yes, it will reset session timeout for 30 minutes through the previous event handler.
The problem is, though user clicks yes, and session timeout is set correctly, session seems timeout before the set time. This only happens after notification.
The suspicion is when it hits Application_AcquireRequestState, the timeout is already calculated for this request. The new timeout value will be used for next request. So when user clicks yes to extend session, the timeout for current request is not 30 minutes away, it is only 3 minutes away, due to timeout set by the notification window. The yes will only be in effect if user sends another request.
(Notification window has its own timing object)
Can anyone verify this? or point me to a good resource to explain how asp.net manages this?
Thanks!
Session.Timeout is a global setting within the application.
If you're setting the users Timeout to 3 minutes when you pop the window notifying the user that they are about to be logged out, and they don't respond, your Session.Timeout will stay at three minutes until another user resets it - is it possible that this is happening?
Zhaph, the problem is when user clicked "Yes" to extend the session, then walk away.
I think I finally nailed down the problem.
It was as I suspected, but only in "SQLServer" mode. When request comes into Application_AcquireRequestState, the session is already extended (can be verified in ASPState database, ASPStateTempSessions table). If user clicked "Yes", though the new time out value is set, it won't be in effect until next server request. If user walked away without another click, session timed out with the previously set timeout value, which is 3 minutes.
In "InProc" or "StateServer" mode, the session objects are managed by cache, whose expiration can be reset only further in the future but not shrink back to more current time (or it will be ignored).
I use a much simpler mechanism. I don't have the popup extend the session at all. I use a session with a sliding window and when the user clicks the "OK" button in the session expiration notification, it makes an AJAX request back to the server updating the sliding window.

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