TimeCoder
TimeCoder

Reputation: 305

Why JWT contains EXP claim even if I set Expires to null?

I need the immortal JWT token. Of course I could set some big value to Expires, but I prefer do not have exp claim in my token at all. Standard .net core CreateEncodedJwt allows to pass null in expires, notBefore, issuedAt. I pass null for all of them, and my token contains exp token (+1 hour). What is going on?!

var securityKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes("FF804E8A-2A0E-4F94-A6F5-8325822F8DF5"));

var claims = new List<Claim>
{
    new Claim("type1", "value1"),
    new Claim("type2", "value2")

};

var token = new JwtSecurityTokenHandler().CreateEncodedJwt(
    issuer: null,
    audience: null,
    subject: new ClaimsIdentity(claims),
    notBefore: null,
    issuedAt: null,
    expires: null,
    signingCredentials: new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256));

This is tool for parsing: https://jwt.io

This is my token:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0eXBlMSI6InZhbHVlMSIsInR5cGUyIjoidmFsdWUyIiwibmJmIjoxNTY1NDI5MzY2LCJleHAiOjE1NjU0MzI5NjYsImlhdCI6MTU2NTQyOTM2Nn0.UvJiOQNO_yMzdenf5jAotPHj7zrcEUApraezzcVSicA

This is how it looks inside:

{ "type1": "value1", "type2": "value2", "nbf": 1565429366, "exp": 1565432966, "iat": 1565429366 }

Please help to get rid nbf, exp, iat. Thanks in advance!

Upvotes: 7

Views: 3564

Answers (1)

cassandrad
cassandrad

Reputation: 3536

Simplified version of JwtSecurityTokenHandle code that creates a token contains the next piece:

if (SetDefaultTimesOnTokenCreation && 
    (!expires.HasValue || !issuedAt.HasValue || !notBefore.HasValue))
{
    DateTime now = DateTime.UtcNow;
    if (!expires.HasValue)
        expires = now + TimeSpan.FromMinutes(TokenLifetimeInMinutes);

    if (!issuedAt.HasValue)
        issuedAt = now;

    if (!notBefore.HasValue)
        notBefore = now;
}

So you basically had to set SetDefaultTimesOnTokenCreation to false. And the standard for JWT says nothing against empty exp claim:

The "exp" (expiration time) claim identifies the expiration time on or after which the JWT MUST NOT be accepted for processing.

Its value MUST be a number containing a NumericDate value. Use of this claim is OPTIONAL.

So all correct implementations of JWT format validators should successfully validate token without that claim inside.

Upvotes: 5

Related Questions