使ASP.NET Core 3中的所有身份验证Cookie无效

发布于 2025-01-25 19:30:47 字数 1497 浏览 5 评论 0原文

在ASP.NET Core 3上,当用户注销时,我想使不同设备上存在的所有cookie无效。用户可能已经从几个不同的浏览器中登录,并且用户可以选择使用持续30天的“记住我”。 到目前为止,我了解解决此问题的理解:

  1. 使用我在用户级别存储在数据库中的SecurityStamp(GUID)(GUID),
  2. 将此安全键列在登录处的索赔中
  3. ,当logout => gt; 当HTTP请求到达具有[授权]属性的控制器的方法时,更改数据库中的安全措辞
  4. ,检查安全键是否匹配数据库中存储的一个。如果不是,请重定向到登录页面。

我的问题是关于点4)在何处以及如何在ASP.NET核心框架中编写此SecurityStamp检查并重定向到登录页面?

这是我在登录时间

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和整个内置身份管理。

On ASP.net CORE 3, when a user logout, I would like to invalidate all the cookies that exist on different devices. The user might have logged in from several different browsers, and the user has the option to use "Remember me" that lasts 30 days.
My understanding to solve this problem so far:

  1. Use a securityStamp (a GUID) that I store in the database at the user level
  2. Add this securityStamp in the Claims at login
  3. When logout => change the securityStamp in the database
  4. When http request arrives on a method of controller with [Authorize] attribute, check if the securityStamp match the one stored in the database. If not, redirect to login page.

My question is about point 4) where and how write this securityStamp check in the ASP.net CORE framework and redirect to login page ?

Here is my code at login time

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

UPDATE:
I have my own user table, I don't use entityFramework and the whole built-in Identity management.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

暮光沉寂 2025-02-01 19:30:47

您可以使用SecurityStamp属性和SecurityStampValidatorOptions.Validation Interval属性,以使登录用户的cookie无效。

1. register validation Interval在配置服务中

services.Configure<SecurityStampValidatorOptions>(options =>
            {
                options.ValidationInterval = TimeSpan.FromSeconds(1);//set your time
                
            });

usermanager.updatesecuritystampasmanc(

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.Add gzmyk.gif“ rel =” nofollow noreferrer“> ”

You can use the SecurityStamp Property and the SecurityStampValidatorOptions.ValidationInterval Property to make the logout user's cookie invalid.

1.Register ValidationInterval in ConfigureServices

services.Configure<SecurityStampValidatorOptions>(options =>
            {
                options.ValidationInterval = TimeSpan.FromSeconds(1);//set your time
                
            });

2.Add userManager.UpdateSecurityStampAsync()in your Logout like below

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

Result:

enter image description here

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文