首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使ASP.net核心3中的所有身份验证cookie无效

使ASP.net核心3中的所有身份验证cookie无效
EN

Stack Overflow用户
提问于 2022-05-03 19:29:14
回答 1查看 645关注 0票数 0

在ASP.net核心3上,当用户注销时,我想使存在于不同设备上的所有cookies失效。用户可能已经从几个不同的浏览器登录,用户可以选择使用持续30天的“记住我”。到目前为止,我对解决这个问题的理解是:

  1. 使用用户级存储在数据库中的securityStamp ( GUID),当http请求到达具有授权属性的控制器方法时,当=>注销时更改数据库
  2. 中的securityStamp时,
  3. 在登录
  4. 的声明中添加securityStamp,检查securityStamp是否与存储在数据库中的securityStamp匹配。如果没有,请重定向到登录页面.

我的问题是关于第4点)在哪里以及如何在securityStamp核心框架中编写这个ASP.net检查并重定向到登录页面?

这是我登录时的代码

代码语言:javascript
复制
string securityStamp = Guid.NewGuid().ToString();
saveSecurityStampInDB(securityStamp, user.Id);
var userClaims = new List<Claim>()
                        {
                            new Claim("id", user.Id.ToString()),
                            new Claim("securityStamp", securityStamp),
                            new Claim("http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider", "ASP.NET Identity", "http://www.w3.org/2001/XMLSchema#string")
                         };
    
    var grantMyIdentity = new ClaimsIdentity(userClaims, "User Identity");
    var userPrincipal = new ClaimsPrincipal(new[] { grantMyIdentity });
    if (rememberMe.HasValue && rememberMe.Value)
    {
           await HttpContext.SignInAsync(userPrincipal, new AuthenticationProperties
           {
                    IsPersistent = true,
                    ExpiresUtc = DateTime.UtcNow.AddMonths(1)
           });
    }
    else
    {
       await HttpContext.SignInAsync(userPrincipal);
    }

更新:我有自己的用户表,我不使用entityFramework和整个内置身份管理。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-05-04 03:16:00

可以使用SecurityStamp属性和SecurityStampValidatorOptions.ValidationInterval属性使注销用户的cookie无效。

1.在ValidationInterval中注册ConfigureServices

代码语言:javascript
复制
services.Configure<SecurityStampValidatorOptions>(options =>
            {
                options.ValidationInterval = TimeSpan.FromSeconds(1);//set your time
                
            });

2.在注销中添加userManager.UpdateSecurityStampAsync(),如下所示

代码语言:javascript
复制
public async Task<IActionResult> Logout()
        {
            var userid = userManager.GetUserId(User);
            var user = await userManager.FindByIdAsync(userid);
            await userManager.UpdateSecurityStampAsync(user);
            await signInManager.SignOutAsync();
 
            return RedirectToAction("Index", "Home");
        }

结果:

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72104560

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档