Search code examples
javajjwt

same expiry date not returned whee set as Claim in signed jwt token


Below is a sample program, that is not returning correct expiry date from claims.

package question;

import io.jsonwebtoken.JwtParser;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;

import java.security.Key;
import java.util.Date;

public class SampleToken {

    public static void main(String[] args) {
        String secretKey = new String("fhsdkjfhksjdfhdjskfhjksdfhjkdshfjksdhfjksdfhjkdshfsdjkhfdksjhfjkdshfdksjhkjfhdskjf");
        byte[] keyBytes = Decoders.BASE64.decode(secretKey);
        Key key = Keys.hmacShaKeyFor(keyBytes);

        Date expirationDate = new Date(System.currentTimeMillis() + 1000 * 60 * 60 * 10);

        String jwt = Jwts.builder().setExpiration(expirationDate).signWith(key).compact();

        JwtParser signedParser = Jwts.parserBuilder().setSigningKey(secretKey).build();

        Date deserializedExpirationDate = signedParser.parseClaimsJws(jwt).getBody().getExpiration();

        System.out.println(expirationDate);
        System.out.println(deserializedExpirationDate);

        System.out.println("date and deserialized dates should be equal : " + expirationDate.compareTo(deserializedExpirationDate));
    }
}

Actual output :-

Sun Mar 14 05:14:25 IST 2021
Sun Mar 14 05:14:25 IST 2021
date and deserialized dates should be equal : 1

Expected output :-

Sun Mar 14 05:14:25 IST 2021
Sun Mar 14 05:14:25 IST 2021
date and deserialized dates should be equal : 0

Solution

  • JWT date precision is to the second while Java dates are millisecond. When dates are serialized the extra precision is lost. You would need to adjust your test.

    It would be easer to notice this problem if you use a ISO 8601 format or, the old standard “getTime()”