【问题标题】:How are JWT tokens updated in cookie?cookie 中的 JWT 令牌如何更新?
【发布时间】:2019-02-12 12:40:49
【问题描述】:

想象一个场景,每次您需要访问服务的某个部分(可通过 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 中,您可以通过login 函数在浏览器中序列化JWT 令牌并设置cookie 值。

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

【问题讨论】:

    标签: c# angular cookies jwt aspnetboilerplate


    【解决方案1】:

    当我创建另一个令牌并设置 cookie 值时,我会覆盖以前的令牌吗?还是之前的token被删除了?

    setCookieValue 中的前一个令牌被覆盖:

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

    【讨论】:

      猜你喜欢
      • 2016-10-12
      • 2020-01-25
      • 2022-12-23
      • 2017-01-02
      • 1970-01-01
      • 2020-06-19
      • 2015-09-15
      • 2016-09-13
      相关资源
      最近更新 更多