Home > Mobile >  Is io.jsonwebtoken.JwtParser multi threaded?
Is io.jsonwebtoken.JwtParser multi threaded?

Time:09-21

Upon every request, I am executing the following (in package io.jsonwebtoken):

Jwts.parser().setSigningKey(secret).parseClaimsJws(token);

Can I create and keep instance field and reuse it for all requests?

JwtParser jp = Jwts.parser().setSigningKey(secret);
public Claims getAllClaimsFromToken(String token) {
        Jws<Claims> c = jp.parseClaimsJws(token);
        return c.getBody();
}

Would getAllClaimsFromToken method be thread safe if I do this?

CodePudding user response:

Jwts.parser() is now deprecated. Please replace it with Jwts.parserBuilder() that returns a JwtParserBuilder. Instances of parsers returned from Jwts.parserBuilder().....build() are immutable (ImmutableJwtParser), which means that you can safely use them in a multithread environment.

JwtParser immutableJwtParser = Jwts.parserBuilder().setSigningKey(secret).build();

public Claims getAllClaimsFromToken(String token) {
    Jws<Claims> c = immutableJwtParser.parseClaimsJws(token);
    return c.getBody();
}

  • Related