如何防止.Net Core 2.x中的多个并发登录?

时间:2019-06-18 08:51:25

标签: login .net-core asp.net-core-identity

我正在尝试限制Web应用程序中的用户登录。某些来源[1]和[2]通过使用await _userManager.UpdateSecurityStampAsync (loginUser);

使用相同的想法

这是AccountController中登录操作的完整代码:

    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Login (LoginViewModel model, string returnUrl = null) {
        ViewData["ReturnUrl"] = returnUrl;
        if ( ModelState.IsValid ) {

            var loginUser = await _userManager.FindByEmailAsync(model.Email);
            if ( loginUser == null ) {
                ModelState.AddModelError (string.Empty, "Invalid username/password.");
                return View ();
            }

            await _userManager.UpdateSecurityStampAsync (loginUser);
            var result = await _signInManager.PasswordSignInAsync(loginUser, model.Password, isPersistent: false, lockoutOnFailure: true);

            if ( result.Succeeded ) {
                _logger.LogInformation ("User logged in.");
                return RedirectToLocal (returnUrl);
            }
            if ( result.RequiresTwoFactor ) {
                return RedirectToAction (nameof (LoginWith2fa), new { returnUrl, model.RememberMe });
            }
            if ( result.IsLockedOut ) {
                _logger.LogWarning ("User account locked out.");
                return RedirectToAction (nameof (Lockout));
            } else {
                ModelState.AddModelError (string.Empty, "Invalid login attempt.");
                return View (model);
            }
        }

        // If we got this far, something failed, redisplay form
        return View (model);
    }

上面的登录操作看起来很熟悉。只需通过添加 UpdateSecurityStampAsync 进行修改,即可在用户每次在 PasswordSignInAsync 之前登录时更新表(dbo.AspNetUsers)中的'concurrencyStamp'和'SecurityStamp'列。

我尝试使用相同的登录名从2个不同的浏览器(从chrome进行的第一次和第二次尝试;从Firefox进行的第三次和第四次尝试)进行屏幕截图。在执行 UpdateSecurityStampAsync 后捕获了第二个和第四个。第二和第三具有相同的 ConcurrencyStamp SecurityStamp

我还在ConfigureServices方法中修改了start.cs:

        services.Configure<SecurityStampValidatorOptions> (option =>
            option.ValidationInterval = TimeSpan.FromSeconds (0)
        );

        services.AddAuthentication ()
            .Services.ConfigureApplicationCookie (options => {
                options.SlidingExpiration = true;
                options.ExpireTimeSpan = TimeSpan.FromMinutes (30);
        });

但是,在修改了上面的代码之后,我仍然可以从其他Web浏览器同时登录。我也可以使用相同的用户名和密码从其他计算机成功登录。

  1. 好吧,我想念什么吗?
  2. 还是 UpdateSecurityStampAsync 不能用于防止用户同时登录?
  3. 或者,.Net Core无法处理 这种情况下,需要第三方进行用户用户登录管理吗?

非常感谢任何帮助/建议。

enter image description here

0 个答案:

没有答案