3

I need to kill the session when the user closes the browser or redirects into some other page. I can see the following options of achieving this functionality:

  1. Use no session login. It's not my case, because I'd have to change a lot and I also use sessions for some other data.
  2. I could use something like this:
window.onunload = window.onbeforeunload = (function () {
   ...
  })

    And from this code call the action that cleans the session and performs logoff. Sounds nasty     but what is also important - this JavaScript code works only in IE.

  1. I could create some nasty code that uses some dummy calls, let's say every minute, just to say the server that the user is still alive. But it's really nasty. It would use useless load on the server, lots of useless calls and in the case if some call was lost(because of the connection issue or something) the user would logg off.

Any other options?

Mouser
  • 13,132
  • 3
  • 28
  • 54
J. Doe
  • 91
  • 4
  • Normally a session is terminated when the users closes all browser windows. The `window.onunload` is a possibility, but you do not know for sure if the request is sent. – Mouser Feb 22 '15 at 10:58
  • Have you looked at Signalr? – rism Feb 22 '15 at 12:38
  • An ASP.Net Session is killed after a timeout, *not* when the user closes the browser / shuts down the computer / looses internet connection – Hans Kesting Dec 12 '17 at 14:52
  • Note that as far as the browser is concerned, "navigating to another page" includes another page within your own application. – Hans Kesting Dec 12 '17 at 14:54

2 Answers2

3

You've left off #4: Don't do anything, have sessions time out after a reasonable period (say, 20 minutes); if they try to do something on that page after being gone for 20 minutes, just show a page telling them their session has expired and to log in again. That's usually the simplest option.

If you don't want to do that, #3 is really your only viable option, but once/minute is probably overkill. Set the session timeout to 20 minutes, remember when the user has done something, and if they're idle for (say) 15 minutes do a proactive call on their behalf. But even then, I'd limit how much I'd do this, after a couple of hours you might want to just redirect them to the login page.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
0

I think this answer is the right way to go:

In javascript, how can I uniquely identify one browser window from another which are under the same cookiedbased sessionId

Set a unique window id:

window.windowIdClient = "{978d-478ahjff-3849-dfkd-38395434}"; //or another randomly generated id.

Store that windowId in the database, along with the ip-address and the session-id. If those three do not match than the user is logged out.

In addition, if didn't think of T.J. Crowder's option, I use it myself.

Community
  • 1
  • 1
Mouser
  • 13,132
  • 3
  • 28
  • 54