Search code examples
springspring-bootspring-securityjwtmicroservices

How do I check if a JWT token is valid in Spring Boot


I've set up a microservice (A) that generates JWT tokens and now I want to validate these tokens in another microservice (B).

How do I validate on (B) that the token generated by (A) is indeed correct? I wan't to simply check if it's valid, has a certain role in the claims, and if yes, to allow for a POST request.

I'm still a beginner to this and don't know how I could do that.

I already got the validation working on microservice (A), but that requires the UserDetailsService to be implemented, which I don't want to do in (B).


Solution

  • For JWT validation in Spring boot, I would recommend using the Maven dependency jjwt

    You can validate a token by creating a method as follows

    //validate token
    public Boolean validateToken(String token, UserDetails userDetails) {
        final String username = getUsernameFromToken(token);
        return (username.equals(userDetails.getUsername()) && !isTokenExpired(token));
    }
    
    //retrieve username from jwt token
    public String getUsernameFromToken(String token) {
        return getClaimFromToken(token, Claims::getSubject);
    }
    
    
    public <T> T getClaimFromToken(String token, Function<Claims, T> claimsResolver) {
        final Claims claims = getAllClaimsFromToken(token);
        return claimsResolver.apply(claims);
    }
    
    //for retrieveing any information from token we will need the secret key
    private Claims getAllClaimsFromToken(String token) {
        return Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();
    }
    

    UPDATE

    @Service
    public class JwtUserDetailsService implements UserDetailsService {
        @Override
      public UserDetails loadUserByUsername(String username) throws 
     UsernameNotFoundException {
        //TODO: return user details object
      }
    }
    
    public static Jws<Claims> parseJwt(String token) {
     Jws<Claims> jwt = Jwts.parserBuilder()
            .setSigningKey(yoursigningkey)
            .build()
            .parseClaimsJws(token);
     //once you have parsed the claims then validate it based on the  
     //user attribute
    }