简体   繁体   English

如何更新存储在 .NET Core 6 中的身份验证 cookie 中的用户声明

[英]How to update user claims stored in authentication cookie in .NET Core 6

I have a Razor Pages app developed using .NET Core 6. The app works as a client and connects to an API.我有一个使用 .NET Core 6 开发的 Razor Pages 应用程序。该应用程序用作客户端并连接到 API。 The API has JWT Access Token/Refresh Token authentication. API 具有 JWT 访问令牌/刷新令牌身份验证。 The login endpoint of the API returns access token and refresh token.Using cookie authentication I store the tokens as claim in authentication cookie. API 的登录端点返回访问令牌和刷新令牌。使用cookie 身份验证我将令牌作为声明存储在身份验证 cookie 中。

var claims = new List<Claim>
        {
            new Claim(ClaimTypes.Name, Login.Email),
            new Claim("Token", loginResponse.Token),
            new Claim("RefreshToken", loginResponse.RefreshToken)
        };

I then get the tokens using extension methods然后我使用扩展方法获取令牌

public static class CommonExtensions
{
    public static string? GetToken(this HttpContext context)
    {
        return context.User.Claims.Single(x => x.Type == "Token").Value.ToString();
    }

    public static string? GetRefreshToken(this HttpContext context)
    {
        return context.User.Claims.Single(x => x.Type == "RefreshToken").Value.ToString();
    }
}

When my access token expires I refresh it, remove existing claims and add new ones with the updated token.当我的访问令牌过期时,我会刷新它,删除现有声明并使用更新的令牌添加新声明。

var identity = User.Identity as ClaimsIdentity;
identity.RemoveClaim(identity.FindFirst("Token"));
identity.AddClaim(new Claim("Token", response.Token));

identity.RemoveClaim(identity.FindFirst("RefreshToken"));
identity.AddClaim(new Claim("RefreshToken", response.RefreshToken));

However the subsequent requests keep using the expired token.但是,后续请求继续使用过期的令牌。 What is the way to update the claims correctly?正确更新声明的方法是什么?

In order to save your changes you would need to call SignInAsync according to Microsoft .为了保存您的更改,您需要根据Microsoft调用SignInAsync

await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, User);

If it does not work, maybe you need to call SignOutAsync first.如果它不起作用,也许您需要先调用SignOutAsync

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM