1

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.

Philiz
  • 429
  • 5
  • 25

1 Answers1

3

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

Qing Guo
  • 6,041
  • 1
  • 2
  • 10
  • In my app, we have our own custom user table, we don't use entityFramework and what comes with built-in Identity management. So I don't know what your "userManager" do when calling "UpdateSecurityStampAsync". Any idea how to handle this then? Thanks – Philiz May 04 '22 at 06:26
  • After finding the current user, "userManager" calling "UpdateSecurityStampAsync", it wants to change the user's [SecurityStamp](https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.identity.usermanager-1.updatesecuritystampasync?view=aspnetcore-6.0#Microsoft_AspNetCore_Identity_UserManager_1_UpdateSecurityStampAsync__0_). This`SecurityStamp` property can set the cookie's valid time. – Qing Guo May 04 '22 at 06:45
  • 1
    ‘ where and how write this securityStamp check’, you can customize an attribute, then in this attribute you can compare the SecurityStamp in database with current SecurityStamp. Or use the new policy design (e.g. `[Authorize( Policy = "YouNeedToBe18ToDoThis")]`) you can read [this](https://stackoverflow.com/questions/31464359/how-do-you-create-a-custom-authorizeattribute-in-asp-net-core) to know more. – Qing Guo May 04 '22 at 07:24
  • 1
    Here is how to implement this https://learn.microsoft.com/en-us/aspnet/core/security/authentication/cookie?view=aspnetcore-6.0#react-to-back-end-changes – Philiz May 05 '22 at 08:39