Search code examples
c#angularcookiesjwtaspnetboilerplate

How are JWT tokens updated in cookie?


Imagine a scenario in which every time you need access to a certain part of a service (obtainable via REST API methods; e.g. access and refresh tokens), you write those tokens into JWT tokens and update cookies in your browser so that you can access those tokens from 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);
}

When you create the JWT token, you get an AuthenticateResultModel in the Authenticate method that is called when the user logs in.

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
    };
}

If successful, the login method is called.

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
    ); 
}

From my understanding, in CreateAccessToken, you serialize the JWT token and set cookie values in your browser via the login function.

Now what I wonder is, when I create another token and set cookie values, do I overwrite the previous token? Or is the previous token deleted? I can't find any information about this topic and the reason I am asking is that I will update this token many times in the lifespan of the application, and I am worried about the storage and memory impact.


Solution

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

    The previous token is overwritten in setCookieValue:

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