I need to sign out a user when the user closed the tab or browser, how do I do that in ASP.NET MVC?
There are a few things you can do to make sure the user is signed out when the browser is closed, but it depends on how you're setting the FormsAuthentication cookie:
Cookieless=True
.FormsAuthentication.SetAuthCookie
to set Persistence to false
window.unload
.Cookieless=True
approach:<system.web>
<authentication mode="Forms">
<forms loginUrl="/Account/Login"
protection="All"
cookieless="true" //set to true
</authentication>
</system.web>
This appends the cookie value to the querystring in each request. The problem with this approach is it's not very secure and it messes with SEO. If a user sends anyone the URL they're using, that person can log in as the original user (probably not what you want). As far as 'messing with SEO', it causes the same page to look different to a googlebot based on what URL is passed in. Each QueryString change makes it a new URL, and if anyone uses this for posting a link; it will dilute the search results for a given actual URL.
FormsAuthenticationTicket
ApproachWhen you set an Authentication cookie for the user, set Persistent to False
.
If you're doing this in the FormsAuthentication.SetAuthCookie
, this is default. If you use the FormsAuthenticationTicket
class, you have to specify the cookie expiration.
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
1, //version
"blah", //Cookie Name
);
FormsAuthentication.SetAuthCookie()
ApproachBy default, if you don't set persistent
, the authentication cookie will expire at the end of the session (when the user closes the browser).
FormsAuthentication.SetAuthCookie("CookieValue", false); //second argument is persistent'
There are no foolproof methods; all you can do is set the cookie expiration date to before now and hope the user's browser co-operates. If you really, really, really, want the cookie gone, you can always try a JavaScript approach, but that won't work if the user has JavaScript disabled.
window.addEventListener('unload', function(event) {
document.cookie = name + '=; expires=Thu, 01 Jan 1970 00:00:01 GMT;';
});
It also matters which browser you use. Chrome has the ability to run in the background, and that keeps Session Cookies around until their timeout is hit -- they are not dropped when the browser is closed (I found this out the hard way).