Logout on browser or tab close

1.9k views Asked by At

I need to log out a user in case he closes the browser/tab running my website. I have set the isPersistant bool to false, yet it does not log the user out. I want force the user to log in again if the tab is closed. I don't want to use jQuery.

Here is some of the relevant snippets from my current code:

AccountController

var result = await SignInManager.PasswordSignInAsync(model.Username,
    model.Password, false, shouldLockout: true);`

Startup.Auth

app.UseCookieAuthentication(new CookieAuthenticationOptions
{
    AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
    LoginPath = new PathString("/Account/Login"),
    Provider = new CookieAuthenticationProvider
    {
        // Enables the application to validate the security stamp when the user logs in.
        // This is a security feature which is used when you change a password or add an external login to your account.  
        OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
        validateInterval: TimeSpan.FromMinutes(5),
        regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))                      
     }
});            

app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5));
app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);
1

There are 1 answers

0
Swifty On BEST ANSWER

As @AndreiV state, there is no way of detecting when the user closes the browser.

I opted to implement SignalR and monitor the connection for a disconnect event, at which point, based on some criteria, I un-authenticate the user's session. If he then comes back the the site, I know that his session is no longer valid and he is redirected to the login page.