浏览器关闭时更新数据库

时间:2015-10-19 14:37:10

标签: c# asp.net-mvc-5

我试图限制用户一次登录多台计算机。为此,我在登录时将数据库中字段的值更改为1,并使用0 LogOff()方法将其重置为AccountController

我希望用户在浏览器关闭时自动注销,因此我在登录时设置inPersistent = false,如下所示:

await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);

问题是,当浏览器关闭时,LogOff()方法未被调用,我无法将我的值重置为0.由于该字段尚未重置为0,该用户将不会能够再次登录。

如何在浏览器关闭时更新我的​​数据库并将该字段重置为0?

4 个答案:

答案 0 :(得分:3)

这是开发事物的坏方法。为什么不在cookie上使用slidingExpiration来使cookie失效。

如果要检查唯一身份用户,则应检查上次使用的会话并使之前使用的会话无效。

这是一个不错的选择吗?

答案 1 :(得分:0)

查找onbeforeunload并对服务器端点进行异步调用,以执行必要的代码。

window.onbeforeunload = function(event) {
  alert("browser closing")
  // to do : Call server 
}

答案 2 :(得分:0)

虽然这不能解答有关浏览器关闭的问题,但可以使用身份SecurityStamp解决此问题。

用户登录后,您可以强制更新SecurityStamp,这样可以使任何其他有效的Cookie无效,并允许用户一次只能在一台计算机上登录。

This answer完美地解释了SecurityStamp

  

因此SecurityStamp的主要目的是在任何地方启用签名。基本的想法是,无论何时在用户上更改与安全相关的内容(如密码),最好自动使任何现有的cookie登录失效,因此如果您的密码/帐户先前已被盗用,则攻击者将无法再访问。

     

在2.0.0中,我们添加了以下配置来挂钩   CookieMiddleware中的OnValidateIdentity方法来查看   SecurityStamp并在更改后拒绝Cookie。它也是   每次自动从数据库刷新用户的声明   如果标记没有改变,则刷新内容(处理事情   喜欢改变角色等)

如果那是你想去的路线; this answer确切地解释了如何在详细信息中完成您正在寻找的内容(最终结果)。

我将提供该帖子的源代码,用于清晰度

基本上你的登录方法看起来像这样。

[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{
if (!ModelState.IsValid)
{
    return View(model);
}


// check if username/password pair match.
var loggedinUser = await UserManager.FindAsync(model.Email, model.Password);
if (loggedinUser != null)
{
    // change the security stamp only on correct username/password
    await UserManager.UpdateSecurityStampAsync(loggedinUser.Id);
}

 // do sign-in
var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: false);
switch (result)
{
    case SignInStatus.Success:
        return RedirectToLocal(returnUrl);
    case SignInStatus.LockedOut:
        return View("Lockout");
    case SignInStatus.RequiresVerification:
        return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
    case SignInStatus.Failure:
    default:
        ModelState.AddModelError("", "Invalid login attempt.");
        return View(model);
}

}

您将在Startup.Auth.cs

中更新您的ConfigureAuth方法
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
    // other stuff
    AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
    LoginPath = new PathString("/Account/Login"),
    Provider = new CookieAuthenticationProvider
    {
        OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
            validateInterval: TimeSpan.FromMinutes(0), // <-- Note the timer is set for zero
            regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
    }
}); 

答案 3 :(得分:0)

使用如下的JavaScript事件:

window.onbeforeunload = function (e) {
    e = e || window.event;

    // For IE and Firefox prior to version 4
    if (e) {
       // write code here
    }
};