asp.net-mvc - 防止多次登录

标签 asp.net-mvc cookies asp.net-identity

我试图在我的应用程序中阻止同一用户的多次登录。我的想法是在用户登录时更新安全戳并将其添加为声明,然后在每个请求中将来自 cookie 的戳与数据库中的戳进行比较。这就是我实现的方式:

        public virtual async Task<ActionResult> Login([Bind(Include = "Email,Password,RememberMe")] LoginViewModel model, string returnUrl)
    {
        if (!ModelState.IsValid)
        {
            return View(model);
        }

        SignInStatus result =
            await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, false);
        switch (result)
        {
            case SignInStatus.Success:
                var user = UserManager.FindByEmail(model.Email);
                var id = user.Id;
                UserManager.UpdateSecurityStamp(user.Id);
                var securityStamp = UserManager.FindByEmail(model.Email).SecurityStamp;
                UserManager.AddClaim(id, new Claim("SecurityStamp", securityStamp));

然后在身份验证配置中我添加了
        app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
            LoginPath = new PathString("/Account/Login"),
            Provider = new CookieAuthenticationProvider
            {
                OnValidateIdentity = ctx =>
                {
                    var ret = Task.Run(() =>
                    {
                        Claim claim = ctx.Identity.FindFirst("SecurityStamp");
                        if (claim != null)
                        {
                            var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
                            var user = userManager.FindById(ctx.Identity.GetUserId());

                            // invalidate session, if SecurityStamp has changed
                            if (user != null && user.SecurityStamp != null && user.SecurityStamp != claim.Value)
                            {
                                ctx.RejectIdentity();
                            }
                        }
                    });
                    return ret;
                }
            }

        });

正如它显示的那样,我试图将来自 cookie 的声明与数据库中的声明进行比较,如果它们不相同,则拒绝该身份。
现在,每次用户登录安全图章时都会更新,但用户 cookie 中的值不同,我不知道为什么?我很怀疑,也许新更新的安全图章没有存储在用户的 cookie 中?

最佳答案

该解决方案比您开始实现的要简单一些。但想法是一样的:每次用户登录时,更改他们的安全标记。这将使所有其他登录 session 无效。因此将教导用户不要共享他们的密码。

我刚刚从标准 VS2013 模板创建了一个新的 MVC5 应用程序,并成功地实现了你想要做的事情。

登录方式。您需要在创建 auth cookie 之前更改安全标记,因为设置 cookie 后,您无法轻松更新值:

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

这样,每次登录都会使用新的安全标记对用户记录进行更新。更新安全戳只是 await UserManager.UpdateSecurityStampAsync(user.Id); 的问题- 比你想象的要简单得多。

下一步是检查每个请求的安全标记。您已经在 Startup.Auth.cs 中找到了最佳挂接点但你又过于复杂了。该框架已经做了你需要做的事情,你需要稍微调整一下:
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))
    }
});            

时间间隔设置为零 - 意味着每个请求的框架都会将用户的安全标记与数据库进行比较。如果 cookie 中的标记与数据库中的标记不匹配,则用户的 auth-cookie 将被抛出,要求他们注销。

但是,请注意,对于来自用户的每个 HTTP 请求,这都会对您的数据库产生一个额外的请求。在庞大的用户群中,这可能会很昂贵,您可以将检查间隔增加到几分钟 - 将减少对数据库的请求,但仍会携带有关不共享登录详细信息的消息。

Full source in github

More information in a blog-post

关于asp.net-mvc - 防止多次登录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31831295/

相关文章:

cookies - Cloudfront 签名 cookie 并同时访问 s3 存储桶中的多个路径

asp.net-core - ASP.NET Core 3.1 同时使用 OpenIDConnect 和自定义 Cookie 身份验证

asp.net - Identity 2.0 Code First 表重命名

asp.net-mvc - Azure ACS + MVC + WCF

c++ - Qt 5.7 QNetworkProxy 没有考虑cookies

c# - 从 App_Data 中的文件获取 XML 数据并将其转换为 IQueryable<MyModel> 的最有效方法?

c# - 如何将 IdentityServer4 与 ASP.NET Microsoft Identity 的自定义密码验证结合使用

asp.net-mvc - 在 asp.net mvc 项目中添加列到创建的标识表?

asp.net - 我是否需要将 Azure 媒体服务和播放器用于纯音频应用程序

c# - 来自具有列表属性的模型的 ASP.NET MVC CheckBoxList