0

I am working on a Spring API that uses JWT authentication. I am trying to extract the "role" claim from the JWT token to determine whether the user is an admin or not. However, even though the JWT token contains the "role" claim, I am still seeing Role extracted from JWT: null in my logs.

Here's what I've tried so far:

  • Checked that the JWT token being sent in the API request contains the "role" claim. I used an online tool to decode the token and verified that the claim is present, it in fact contains the role "admin" which is what im looking for.
  • Added print statements to the code that generates the JWT token to check that the "role" claim is being added to the token correctly. The print statements confirm that the "role" claim is being added with the correct value.
  • Added print statements to the JWT parsing code to check that the "role" claim is being extracted correctly. However, the logs still show Role extracted from JWT: null.
  • Checked that the JWT token being sent in the API request matches the one being generated by the code. I printed the entire JWT token being sent in the API request and compared it to the one being generated by the code, and they appear to be the same. Here's the relevant code:
// Code that generates JWT token
    private String createToken(Map<String, Object> claims , String subject){
        return Jwts.builder()
                .setClaims(claims)
                .setSubject(subject)
                .setIssuedAt(new Date(System.currentTimeMillis()))
                .setExpiration(new Date(System.currentTimeMillis()+1000*60*60*2))
                .signWith(SignatureAlgorithm.HS256,secret).compact();
    }
    public boolean isAdmin(){
        System.out.println("Role extracted from JWT: " + claims.get("role"));
        return "admin".equalsIgnoreCase((String) claims.get("role"));
    }

Does anyone have any suggestions on what else I could try to resolve this issue? Any help would be greatly appreciated!

1 Answers1

0

I think this can give you an idea how to solve you problem.

Firstly, you need to generated a JWT token with the roles claim.

public String generateToken(Map<String, Object> extraClaims, UserDetails userDetails) {
  List<String> roles = new ArrayList<>();
  Map<String, Object> rolesClaim = new HashMap<>();
  userDetails.getAuthorities().forEach(a -> roles.add(a.getAuthority()));
  rolesClaim.put("roles", roles);

  return Jwts
          .builder()
          .setClaims(extraClaims)
          .setIssuer(issuer)
          .setAudience(audience)
          .setSubject(userDetails.getUsername())
          .setIssuedAt(new Date(System.currentTimeMillis()))
          .setExpiration(new Date(System.currentTimeMillis() + 1000 * 60 * 10)) // 10 minutes
          .signWith(getSignInKey(), SignatureAlgorithm.HS256)
          .addClaims(rolesClaim)
          .compact();
}

Secondly, you can extract the roles claim.

Claims extractAllClaims = Jwts
          .parserBuilder()
          .setSigningKey(getSignInKey())
          .build()
          .parseClaimsJws(token)
          .getBody();

List<String> claimRoles = extractAllClaims.get("roles", List.class);
Galkin
  • 791
  • 2
  • 9
  • 25