Logout solution (ASP.NET) - asp.net

I programmed a web site, prepared a login mechanism(via textbox, not Login tools), users want to logout, they click logout button. However, my problem is that if users don't click logout button or close web page or switch another one, How can I understand this situation?
According my mechanism, when users logout ,in DB some insertion and delete operation are making.
I also want to do this with closing page,switch another one.
Thanks.

It sounds like you're doing a DB operation on logout, and when people just navigate away without clicking the logout button, the code doesn't fire.
In your global.asax, take a look at session_end. Maybe you can put your operation in there.
protected void Session_End(Object sender, EventArgs e)
{
// Your code goes here. Since your logout code probably relied on the user being
// logged in, you might end up checking Request.IsAuthenticated here. Why? Because
// this event fires any time a session ends -- even if the user is not logged in!
}
Note that if you use this, it actually fires when the IIS session ends, not when the browser closes. By default the session times out after 20 minutes of inactivity.
Once you implement this, you could have your logout page call Session.Abandon, which will trigger Session_End. That seems clean to me.
Here's an MSDN link with some more details on session events: http://msdn.microsoft.com/en-us/library/ms178583.aspx

Session end is probably your best bet as previously mentioned, but if you're paranoid, you can put some javascript/AJAX on your page that pings your server every X seconds to basically say "I'm still here". Then if they leave, instead of waiting the whole 20 minutes or so for the session to end, you can know within X seconds that they've left, since they're not pinging anymore.

If your session timeout is 20 minutes you will only detect after 20 minutes that the session has ended = the user has left your page. You can detect the session end in the global.asax session_end like Brian describes.
If you want to detect someone leaving your page earlier - say after a minute, you could reduce the session timeout to 1 minute.
The problem is then, if the user doesn't do anything on your page - no post back to the server - his session will timeout despite him still viewing your page.
To get around this you could use a keep alive mechanism. Your Page would call the server regularly in the background as long as the user views your page. This can be done with AJAX Javascript or oher mechanisms like hidden iFrame.
See for example: ASP.NET AJAX and keeping the Session alive - What is the standard way to do it?

I am not entirely sure, but I think one way this is implemented is to not set an expiration on a cookie, which will cause it to be a session cookie that is lost when the browser is closed. Since your session cookie typically contains the session key, then they will essentially be starting a new session when they open up a browser again.

When I make users system, I add to database table with users that are login (something like session) and i gave them timestamp. Every refresh of site I run query to delete users with timestamp older then 30 minutes. This is very easy solution, maybe there is better way.

might want to check out the events in global.asax. You can update the db with the session_end event. You can also use the beginrequest event which is fired on each page and control (you'll get multiple hits per page if you have multiple controls). You could also put something in your page_load event.

Related

how to prevent session abandonment for idle user (session wise)

I have a page on my web app where users might use for potentially hours with no server interaction. all interactions are done on the page with javascript.
how can I prevent a session abandonment if I do want to have it set for 20 minutes on all other pages?
my solution is sending an empty ajax call every 10 minutes just to tickle the server, but is there any other option?
You can make a dummy ajax call to renew the session timeout.
To do this, create an empty .aspx page, and use whatever you want to load that page to renew the session. For example, a JavaScript setInterval and a jquery $.get()
If you don't fill comfortable using JavaScript and jQuery, you always can use an Ajax Timer' and another AjaxUpdatePanel`.
This guarantees that the session will keep alive while the browser is open.
Making all sessions longer doesn't look like the best possible solution.
Dependign on where you need this functionality, you can implement it on a master page, or include it where needed. You can even include it in the masterpage and enable or disable the timer.
In ASP.Net, you can change Session.Timeout before returning to extend it on that page. I have not tested whether or not it would un-extend on other subsequent requests, but it would be worth looking at.
http://msdn.microsoft.com/en-us/library/ms524319(v=vs.90).aspx

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

How to abandon session if user X's out of browser?

Is there a way to do a Session.Abandon() when the user just kills the session by X'ing out with the little red X box in the upper right corner? I am seeing situations where after an "X out", the user comes back in and it seems like session variables are still present? I guess explorer keeps them intact? (I am unsure of this).
You can try doing an AJAX type callback in the OnUnload event - however, as someone else mentioned you'd have to be aware of other tabs being open (not easy), and it still won't guarantee you get that event.
There's a combination of things to do to get a similar type of effect.
Session Cookie should have a null/empty expiry time. This ensures the browser deletes the session from it's end after the browser is closed.
The ASP Session can be set with a short SessionState timeout value. This means if there's no client activity within that period, the Session will expire.
The side effect of this is that if a user is just looking at the site, and not performing activity (regardless of whether the browser is still open) - the session can expire.
This can be worked-around by having a Javascript timer periodically ping back to the server with an AJAX call or similar. The side effect of THIS is that it generates more site traffic.
The server is typically not aware of such events on the client. The only way the server can be notified about anything is if there is a request sent back to it. I guess you could create such a notification in a JavaScript, but then you should also keep in mind that the session in mind that the session is not per-page but (usually) per user, which means that you would need to keep track of how many tabs/windows the user has opened so that you don't kill the session when you should not.
Personally, I usually try to design the web apps so that they live well with the default handling of sessions, either providing a specific "Logout" command that will kill the session, or simply let it hit the timeout and die.

asp.net sessions issue

I have a problem of the session not expiring. Here is my case
I have a application in asp.net1.1. i am able to handle session when user click logout button. Session is active for 35 minutes. the application is also check if same user is trying to login using multiple machine and blocks it.
Now this application is deployed in city where there is power outage. When user is loggd in and light goes off, the session remain open. Due to this, the user is not able to log in again for next 35 minutes from alternate machine.
Can you tell solution of how to handle issue of session remained open the right way?
Did you write the code that if a session already exists, refuse another login? If so, you will probably have to change it. It is more common to kill the old session and start a new one if necessary. I prefer to allow multiple sessions for a single user unless there is some specific security requirement not too.
Lookup the SessionState timeout field in Web.config.
Best solution is to add UPS to the client workstations so they don't lose the connection if the power goes out. The only other option I can think of in this situation is to add something to the login code which, instead of blocking an alternate location login, instead forces the other session to be expired on a successful login.
We solved some similar issue this way:
in the body of the asp.net page, we attach on the onload event an ajax call. In this ajax call, the session timeout is set to 35 mins.
Also an ajax call is attached to the onunload, where we set the session timeout to 1 min.
This way the user has 35 min timeout when using the application, yet has 1 minute timeout when closing the application.

Resources