views:

837

answers:

3

In one of the ASP.NET MVC apps we would like to logoff the user automatically if he closes the browser tab in which the app is opened.

We are using the following code when he authenticates.

FormsAuthentication.SetAuthCookie(userName, false)

As of now, if we closes the browser window and relaunch it, users are asked to authenticate again. But we want to ask users to authenticate again if they close the tab and try to access any of the website urls.

+2  A: 

I have not tried this myself, but I think the following approach should work:

On the client side, you can use the OnUnload event of your document to launch a javascript function that would call your server-side signout method via ajax.

On the server side, you should have the action method call FormsAuthentication.SignOut() and Session.Abandon();

Adrian Grigore
Be careful with this, though, as the onunload fires when navigating away from the page as well. And as far as I know, there isn't any way to check if the user is navigating or closing...
peirix
unload is fired before moving to every page of the website. But I want to handle tab close.
Gopinath
Sorry, I forgot that you might not be writing an AJAX website. I am loading all new content via AJAX calls (using a custom-made jquery plugin), so I only get an unloadevent when the tab or window is closed.
Adrian Grigore
+1  A: 

A browser clears all Session scoped objects only when it is completely closed, and not when an individual tab is closed.

One way could be to use a very low Session timeout and have a server-side script poll every few seconds to hit an object on the page. This will extend Session time again. So if a tab is closed, the script can't find the object thereby allowing the Session to timeout. One problem here is if your app is on a pretty high load, your app could DoS itself!

Druid
+1  A: 

We decided to use cookie less authentication so that the authentication token is part of the url. When the tab is closed and they open the website again, they will be asked to authenticate again :)

Gopinath
I'm afraid this might not be a good approach in SEO aspect.
CD
This means that authentication tokens are going to be saved in a lot more places then you expect - many corporate firewalls and other filters log the url. Even your own website logs will show them (meaning that you just gave any network admin or data center employee with basic file access the ability to impersonate users by copying the url from the standard IIS/Apache log file)
David