在浏览器或选项卡关闭时注销

Logout on browser or tab close

我需要注销用户以防他关闭 browser/tab 运行 我的网站。我已将 isPersistant 布尔值设置为 false,但它不会注销用户。如果选项卡关闭,我想强制用户再次登录。我不想使用 jQuery.

这是我当前代码中的一些相关片段:

账户控制器

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);

正如@AndreiV 所说,无法检测用户何时关闭浏览器。

我选择实施 SignalR 并监视断开连接事件的连接,此时,根据某些标准,我取消对用户会话的身份验证。如果他随后返回网站,我就知道他的会话不再有效,他将被重定向到登录页面。