jwt icon indicating copy to clipboard operation
jwt copied to clipboard

Expiry Time is added to claims when decoding

Open pluethi1 opened this issue 3 years ago • 3 comments

Hi

Just wanted to clarify wether this is intended behaviour or a bug.

I have a backend which generates both refresh and access tokens with different expiry times. The refresh token's purpose is to generate new acccess tokens.

I generate either token with the following snippet:


var claims = new Dictionary<string, object>
{
    ["name"] = "Peter",
    ["role"] = "User",
};

var token = JwtBuilder.Create()
    .WithAlgorithm(myAlgorithm)
    .ExpirationTime(DateTime.Now.AddSeconds(180))
    .AddClaims(claims)
    .Encode();

And decode the token back to claims with this snippet:


var claims = JwtBuilder.Create()
    .WithAlgorithm(myAlgorithm)
    .Decode<Dictionary<string, object>>(token);

The issue is now, after decoding the claims the expiry time is added to the claims dictionary with the key 'exp'. So when I reuse the claims dictionary to generate a new token, it throws a DuplicateKeyException due to the expiry time already being present in the claims dictionary.

To circumvent this I just remove the 'exp' key from the dictionary before reusing it.

Could anyone clarify if this is intended or not?

Cheers Phil

pluethi1 avatar Sep 13 '23 07:09 pluethi1

Hi Phil, thanks for reaching out! Can you please provide a more detailed code snippet, e.g. a test which would fail, to illustrate the issue? Happy to look into it.

abatishchev avatar Sep 13 '23 16:09 abatishchev

Or maybe it's not needed. So this code:

.ExpirationTime(DateTime.Now.AddSeconds(180))
.AddClaims(claims)

does this:

1.

https://github.com/jwt-dotnet/jwt/blob/2c76ee09c4f8cadcb7347a8f9748c63086360edc/src/JWT/Builder/JwtBuilderExtensions.cs#L37-L38

2.

https://github.com/jwt-dotnet/jwt/blob/2c76ee09c4f8cadcb7347a8f9748c63086360edc/src/JWT/Builder/JwtBuilderExtensions.cs#L31-L32

https://github.com/jwt-dotnet/jwt/blob/2c76ee09c4f8cadcb7347a8f9748c63086360edc/src/JWT/Builder/JwtBuilder.cs#L74-L78

3. https://github.com/jwt-dotnet/jwt/blob/2c76ee09c4f8cadcb7347a8f9748c63086360edc/src/JWT/Builder/JwtBuilder.cs#L284

4. https://github.com/jwt-dotnet/jwt/blob/2c76ee09c4f8cadcb7347a8f9748c63086360edc/src/JWT/JwtEncoder.cs#L66

So it seems it's you who's adding the exp claim to the payload. Makes sense?

abatishchev avatar Sep 13 '23 16:09 abatishchev

Hi and Thanks for replying

Ok makes sense to me, should've read the JWT spec a bit closer :) As I can see this is intended but it's no biggie as I can just circumvent this as I stated in the initial question.

I'll close this issue as resolved

Cheers Phil

pluethi1 avatar Sep 27 '23 09:09 pluethi1