Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JWT token expiration check

Tags:

java

jwt

I've a following utility class but whenever I check for an expired Token via verify method, it's not throwing the JWtVerificationException.

public class Token {

    private static String SECRET = "c3bff416-993f-4760-9275-132b00256944";

    public static String get(String name, String value) throws UnsupportedEncodingException {
        return JWT.create()
                .withIssuer("auth0")
                .withClaim(name, value)
                .withClaim("random", String.valueOf(UUID.randomUUID()))
                .withExpiresAt(new Date(System.currentTimeMillis() + (4 * 60 * 60 * 1000)))
                .sign(Algorithm.HMAC256(Token.SECRET));
    }

    public static DecodedJWT verify(String token) throws JWTVerificationException, UnsupportedEncodingException {
        JWTVerifier verifier = JWT.require(Algorithm.HMAC256(Token.SECRET))
                .withIssuer("auth0")
                .acceptExpiresAt(4)
                .build();

        return verifier.verify(token);
    }

}

As per the website https://github.com/auth0/java-jwt

When verifying a token the time validation occurs automatically, resulting in a JWTVerificationException being throw when the values are invalid.

Edit:

A case when client renewing token every 5 minutes, will following work or should I add few extra seconds to accommodate any network lag?

creates

.withExpiresAt(new Date(System.currentTimeMillis() + (5 * 60 * 1000))) // 5 minutes

verify

.acceptExpiresAt(5 * 60) // accept expiry of 5 minutes
like image 588
Developer Avatar asked Sep 11 '25 09:09

Developer


1 Answers

JWT.create().withExpiresAt(new Date(System.currentTimeMillis() + (5 * 60 * 1000))) means you will create a token, which will expire after 5 minutes. It seems good.

JWT.require(xxx).acceptExpiresAt(5 * 60) means you will accept a token which has already expired 5 minutes before.Even considering the network lag, 5 minutes of leeway is still too long. It should in seconds.

like image 68
John Avatar answered Sep 14 '25 00:09

John