Search code examples
javajwtjjwt

JJWT Tokens. How do I set timeout?


Using the jjwt library,

 String compactJws = Jwts.builder().setSubject("Joe").signWith(SignatureAlgorithm.HS512, key).compact();

But this token is permanent, how do I set some kind of timeout on this?


Solution

  • Date expiration = getExpirationDate(); // implement me
    
    Jwts.builder().setSubject("Joe")
        .setExpiration(expiration)
        .signWith(SignatureAlgorithm.HS512, key)
        .compact();
    

    Per the JWT specification, the date will be converted into the number of seconds (not milliseconds) since epoch and stored as the exp JWT claim. A parser will look at that claim and ensure that the JWT is not expired.

    Note that expiration checks are based on system clock time at the time of parsing. If the machine that generated the token has a clock that has drifted reasonably compared to the machine that parses the token, your expiration checks could fail. In this case, you can use JJWT's setAllowedClockSkewSeconds method (on the JwtParser/Builder) to allow for some wiggle room on the differences between clocks (1 to 2 minutes should be more than enough), for example:

    Jwts.parser().setAllowedClockSkewSeconds(120)...etc...
    

    if for whatever reason that may not be good enough, you can control the actual parsing clock via:

    Jwts.parser().setClock(new MyClock())...etc...
    

    Setting a Clock shouldn't be necessary in most cases however (it's usually most useful in test cases).