How to safely destroy a session when leaving a site? - javascript

I'm looking for a well-supported way to capture a user leaving a page -- by typing in a new URL, clicking a bookmark, etc. -- to destroy the session so that a person cannot use the 'back' button to return to the site logged in.
Searches have turned up body onbeforeunload=..., an IE-ism that is supposedly supported by other current browsers, but is there a better or more official browser- and server side technology-neutral HTML/JavaScript way to do this?

The only way to do that, imo, is to use a keep alive on a short leash from your site. I.E. do an ajax keep alive to the server to keep your session active, and if they browse away, the keep alive disappears and thus the session expires. Kinda a brute force method though...

Related

On iOS, is there a way to detect a web page runs in the embedded browser and open the "real" one?

My web site uses magic links for login, however, I have a problem on mobile (not sure about Android - haven't tried yet, but the problem exists at least on iOS): when a user receives the email say in the GMail app, the link opens in the embedded browser, meaning that cookies will not be passed to the "real" browser.
Is there a way to ensure the link in the email opens in the real system browser and therefore cookies are stored permanently?
(Essentially browser session isolation on iOS breaks a lot of things on the Internet, so surely there is a workaround?)
After some research: no, it is not possible to detect you are in an embedded browser, neither is it possible to enforce opening a link in the system one. Makes sense from security point of view.
However, I was asking the wrong question. The problem of a magic link login is solved differently: when starting a login process you can set a session cookie and create an associated DB record for it, marking it as blocked, i.e. not logged in.
At next step, when the magic link is opened in whatever browser you unblock the session in the DB. At this stage you can replace the login cookie with a real one, e.g. JWT, or continue using it as your main auth token.
If the user then returns to the real browser, you check the login cookie and act accordingly, keeping in mind that it may not be the browser where they validated the magic link. At this stage you can, again, replace the login cookie with your real auth cookie knowing that the session has been validated already.
I'm not entirely sure this is 100% safe, need to think about it more but at first glance it does look safe and seems to be pretty much the only way of handling magic links on mobile.

Detecting Browser Close or Tab Close without Impacting other functionality

I want to invalidate the session when the user close the tab or browser in my GWT Application. I saw lot of threads Confirm Browser Exit in GWT but didn't get the solution which i am looking for. This should not fire when user refresh the browser(it shouldn't invalidate the session) and even it should not fire when user navigate to other screen or download any file.Any Idea?
There is no way to tell the difference between closing a window or navigating away in various ways. You may be able to get around refreshing a page issue by creating a timer on the server side to see if a user requests your page again within a certain period of time, but it's not clear what benefits you get.
From a user experience view, you should offer a Sign Out (Log out) button or something similar, so a user can clearly indicate an intent to leave your app. Also, you can set an inactive timeout on your session, to invalidate session after a period of inactivity.

How to detect/stop a user opening a new browser window?

This is in context to an ASP.Net application. The application makes use of a specific data which is set for a page. After this data has been set all the operations from this page onwards use the set data.
The problem is that if the user opens another tab with a competing data it overwrites the older data for the same session and for the same user which invalidates the operations on the first tab.
I know the suggested way is to refactor the code to remove such coupling but that is not possible. Here's another thread that discussed this but didn't specify any solutions other than refactoring the code (http://stackoverflow.com/questions/632062/ways-to-detect-ctrl-n-or-when-a-user-opens-a-new-window)
So, how can I detect (and notify the user) or stop the user from opening another tab - through javascript/Jquery?
You could set a session variable isActive and set it to true, along with all the other session data when the user opens the application the first time. After this, if the user opens another tab, check to see if isActive is true. If it is, inform the user and don't set the data again.
In pseudo-code, your logic should flow like this
if (!isActive)
//set session data
else
//alert the user: You have another active session
This would be a better solution because there is no guarantee the user does not visit the page to set the session, then temporarily turn off Javascript to launch a new tab without you being notified.
You should realize that you cannot prevent multiple pages being open on the same site by the same user. A user can always do such an operation using multiple different browsers on the same computer or browsers on different computers. As such, what you really need to do is to design your application to either just handle this situation gracefully or detect such a conflict and decide what the safest action is to take when it occurs (chances are, at the server, you either ignore the data from all sessions but one or you somehow merge them all together). What the safe action is depends upon what the data is or how it was changed.
The most straightforward option is to coin a new server-based session for the user each time the user visits and, at the server, invalidate all previous sessions so any older session that tries to make any future updates to the server will be denied because of an invalid session. This prevents any sort of multi-session data conflict.
If you want to be able to inform the user when their session becomes invalid, you could do a slow poll of the server (say once every 20 mins) as long as the window is open and on your site to check the session validity such that you can inform the user when their session has expired.

How to sync with server and clear session before the user leaves a page?

Is there any way to detect when a user leaves a page, no matter if it's by closing the browser, entering a new URL in the address bar, clicking on a link that redirects to other domain, etc. ?
The main purpose of this would be to perform some activities such as:
sync with the server some data that resides in the client side
clear server session
I was trying with the window's unload and beforeunload events, and reading other questions like:
Best way to detect when a user leaves a web page?
//
Is there any way to know that user leaving a page with asp.net? but I didn't find the answer I would expect.
Here is a simplified js snippet to understand what I was trying:
window.onunload = function(){
if (theConditionThatINeed){
doThings();
SyncWithServerAndAbandonSession(url, localObjects);
}
else {
doNothing();
}
}
I don't want to display any kind of confirmation before the user leaves, so I think that the onbeforeunload won't help me here.
Supposing that the answer is "there is no way to do such thing", what would be the recommended practice to accomplish the synchronization and session clearing that I want?
The primary browser that I support is IE >= 7
As you already read, it is not reliably possible to detect whether the user leaves your page.
Generally it is not good practice to store any unsynced state on the client side. Browsers are easily closed or crashed.
You can send yourself ajax keepalive messages via javascript, in case the user does anything on your page. Again, very unreliable, wasteful and hacky.
Auto-Sync after a short timeout.
Take a look at RESTful web applications. The concept is interesting, and, very superficially spoken, discourages keeping state information on the server. You can apply this to the client as well.
This usually results in keeping state information in the URL. The URL tells the server anything it needs to know to service the request, it should not need a memory (the session) of any previous activity.
I try to only keep the user identification info in the session. I would get rid of this too, but some tools and libs need the user in the session.

Saving the time the user is logged on

In the application I am developing I have to store the time some particular users remain logged into the application, unfortunately, in web applications, there are several ways the user can log off.
User clicks log off.
User session expires.
User closes the window.
User types another site URL in the address bar.
The first one is quite easy because the application gets control of the logging off process. But in the other ones, it gets tricky.
What would you do to solve this problem?
On each page view, update your count. If they log out, then you've got an accurate measure. If they navigate away, or any other method, then the most that you're out is the length of time they were on one page.
If it were really really important to have an accurate measure, then perhaps an AJAX "heartbeat" every minute, but that's most likely overkill.
Well for #3 and #4 you can attach something to the window.onunload event that gets you the time for calcuations, but be careful that your code is fast enough that the page doesn't completely unload before your AJAX request can be sent.
As far as #2 goes, the "heartbeat" suggested by nickf is probably the best solution there.

Categories