JWT 令牌如何在 cookie 中更新?

How are JWT tokens updated in cookie?

想象这样一种场景,每次您需要访问服务的特定部分(可通过 REST API 方法获得;例如访问和刷新令牌),您将这些令牌写入 JWT 令牌并更新 cookie在您的浏览器中,以便您可以从 AbpSession.

访问这些令牌
private string CreateAccessToken(IEnumerable<Claim> claims, TimeSpan? expiration = null)
{
    var now = DateTime.UtcNow;

    var jwtSecurityToken = new JwtSecurityToken(
        issuer: _configuration.Issuer,
        audience: _configuration.Audience,
        claims: claims,
        notBefore: now,
        expires: now.Add(expiration ?? _configuration.Expiration),
        signingCredentials: _configuration.SigningCredentials
    );

    return new JwtSecurityTokenHandler().WriteToken(jwtSecurityToken);
}

当您创建 JWT 令牌时,您会在 Authenticate 方法中获得一个 AuthenticateResultModel,当用户登录时将调用该方法。

public async Task<AuthenticateResultModel> Authenticate([FromBody] AuthenticateModel model)
{
    // ...

    return new AuthenticateResultModel
    {
        AccessToken = accessToken,
        EncryptedAccessToken = GetEncrpyedAccessToken(accessToken),
        ExpireInSeconds = (int)_configuration.Expiration.TotalSeconds,
        UserId = (long)AbpSession.UserId
    };
}

如果成功,将调用 login 方法。

private login(accessToken: string, encryptedAccessToken: string, expireInSeconds: number, rememberMe?: boolean): void {

    var tokenExpireDate = rememberMe ? (new Date(new Date().getTime() + 1000 * expireInSeconds)) : undefined;

    this._tokenService.setToken(
        accessToken,
        tokenExpireDate
    );

    this._utilsService.setCookieValue(
        AppConsts.authorization.encrptedAuthTokenName,
        encryptedAccessToken,
        tokenExpireDate,
        abp.appPath
    ); 
}

据我了解,在 CreateAccessToken 中,您序列化 JWT 令牌并通过 login 函数在浏览器中设置 cookie 值。

现在我想知道的是,当我创建另一个令牌并设置 cookie 值时,我是否会覆盖之前的令牌?还是之前的token被删除了? 我找不到关于这个主题的任何信息,我问的原因是我会在应用程序的生命周期内多次更新此令牌,我担心存储和内存影响。

when I create another token and set cookie values, do I overwrite the previous token? Or is the previous token deleted?

之前的标记在setCookieValue中被覆盖:

abp.utils.setCookieValue = function (key, value, expireDate, path, domain) {
    var cookieValue = encodeURIComponent(key) + '=';

    if (value) {
        cookieValue = cookieValue + encodeURIComponent(value);
    }

    // ...

    document.cookie = cookieValue;
};