如何在Cookie中更新JWT令牌?

时间:2018-09-07 07:49:33

标签: c# angular cookies jwt aspnetboilerplate

想象一个场景,其中每当您需要访问服务的某个部分(可通过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令牌时,您会在AuthenticateResultModel方法中获得Authenticate,该方法在用户登录时会调用。

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中,您将通过login函数序列化JWT令牌并在浏览器中设置cookie值。

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

1 个答案:

答案 0 :(得分:0)

  

当我创建另一个令牌并设置cookie值时,是否会覆盖以前的令牌?还是先前的令牌已删除?

先前的令牌在setCookieValue中被覆盖:

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

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

    // ...

    document.cookie = cookieValue;
};