Home > Mobile >  How to validate Jwt token?
How to validate Jwt token?

Time:07-22

I was exploring Spring security through two tutorials. In one of the tutorials jwt token is validated as follows:

public boolean validateToken(String authToken) {
    try {
        Jwts.parser().setSigningKey(appProperties.getAuth().getTokenSecret()).parseClaimsJws(authToken);
        return true;
    } catch (SignatureException ex) {
        logger.error("Invalid JWT signature");
    } catch (MalformedJwtException ex) {
        logger.error("Invalid JWT token");
    } catch (ExpiredJwtException ex) {
        logger.error("Expired JWT token");
    } catch (UnsupportedJwtException ex) {
        logger.error("Unsupported JWT token");
    } catch (IllegalArgumentException ex) {
        logger.error("JWT claims string is empty.");
    }
    return false;
}

while in another tutorial, it is validated as follows:

public String extractUsername(String token) {
    return extractClaim(token, Claims::getSubject);
}

public Date extractExpiration(String token) {
    return extractClaim(token, Claims::getExpiration);
}

public <T> T extractClaim(String token, Function<Claims, T> claimsResolver) {
    final Claims claims = extractAllClaims(token);
    return claimsResolver.apply(claims);
}
private Claims extractAllClaims(String token) {
    return Jwts.parser().setSigningKey(SECRET_KEY).parseClaimsJws(token).getBody();
}

private Boolean isTokenExpired(String token) {
    return extractExpiration(token).before(new Date());
}

public Boolean validateToken(String token, UserDetails userDetails) {
    final String username = extractUsername(token);
    return (username.equals(userDetails.getUsername()) && !isTokenExpired(token));
}

I have few doubts:

Q1. The second example does no catch exceptions. Should catching and logging exceptions ideally be part of validation or not? Or the second example is indeed doing something similar which I am not able to spot?

Q2. Token expiry is handled by catching ExpiredJwtException, whereas second example explicitly checks for token expiry with isTokenExpired(). How it should be ideally done?

Q3. Second example explicitly checks whether username in token is indeed same as the username in the current security context with username.equals(userDetails.getUsername()). I dont know how it wont be, as I believe security context itself will be populated using current token. Thus I feel that this condition will always be trivially true. Am I correct? Also is this the reason why first example is not checking explicitly for this?

CodePudding user response:

The second example does no catch exceptions. Should catching and logging exceptions ideally be part of validation or not? Or the second example is indeed doing something similar which I am not able to spot?

According to me we should catch exceptions and should be wrapped in business exceptions with error codes because it becomes easier to troubleshoot .

CodePudding user response:

Both of them are faulty since both of them are implementing custom security which in general is bad practice.

Writing a custom validation of something as important as tokens is not needed if you are using spring security since spring security has had full JWTSupport for several years now.

The documentation has an entire chapter on how to configure the built in JWTFilter that comes with spring security, and its as easy as just adding one single line.

https://docs.spring.io/spring-security/reference/servlet/oauth2/resource-server/jwt.html#oauth2resourceserver-jwt-architecture

Standard enabling of the jwt filter:

@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
    http
        .authorizeHttpRequests(authorize -> authorize
            .anyRequest().authenticated()
        )
        .oauth2ResourceServer(OAuth2ResourceServerConfigurer::jwt);
    return http.build();
}

Configure how your jwt should be verified:

@Bean
JwtDecoder jwtDecoder() {
    return NimbusJwtDecoder.withSecretKey(this.key)
            .jwsAlgorithm(RS512).build();
}

There are several other things to configure.

  • Related