Issue while parsing JWT for claims

Viewed 2001

I want to fetch the roles stored as claim in JWT. I am using following code to do that:

   DecodedJWT decodedJWT = JWT.require(Algorithm.HMAC512(SecurityConstants.SECRET.getBytes()))
                    .build()
                    .verify(token.replace(SecurityConstants.TOKEN_PREFIX, ""));
  String user = decodedJWT.getSubject();
  Claim claims = decodedJWT.getClaims();
  String roles = claims.get("roles").toString();

But this ends up giving object code:

 (Value of roles)JSONNodeClaim@10091

I debugged the code and found claims like this:

enter image description here

How can i extract the "ROLE_ADMIN" ?

3 Answers

You can cast the claim to the Claim class and call the .asString() method to return it as a string:

String claims = ((Claim) decodedJWT.getClaim("roles")).asString();

You can use the chain method call to get the below:

String claims = decodedJWT.getClaim("roles").as(TextNode.class).asText();

The roles are always multiple, hence need to call with extraction as a collection

List<SimpleGrantedAuthority> simpleGrantedAuthorities = decodedJWT.getClaim("role").asList(SimpleGrantedAuthority.class);
Related