Home > Mobile >  Some troubles while parsing Auth0 JWT Claims
Some troubles while parsing Auth0 JWT Claims

Time:04-07

public Map<String, String> verifyToken(final String token) throws NoSuchAlgorithmException, InvalidKeySpecException {
    final Algorithm algorithm = Algorithm.RSA256(getPublicKey());
    final JWTVerifier verifier = JWT.require(algorithm).withIssuer(tokenConfiguration.getIssuer()).build();

    try {
        final DecodedJWT decodedJWT = verifier.verify(token);
        return decodedJWT.getClaims().entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, x -> x.getValue().toString()));
    } catch (final JWTVerificationException jwtVerificationException) {
        throw new RuntimeException();
    }
}

I have this code which basically verify the token and retrieve claims as HashMap

final String phone = Optional
        .ofNullable(claimMap.get("phone"))
        .orElseThrow(() -> new RuntimeException());

When I trying to get phoneNumber from Hashmap, it return correct phone but "" 1231551921"" wrong fashion. How to get rid of extra quotes?

My questions is how can i parse JWT claims with correct way ?

My jwt token with RSA-256:

eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJwaG9uZSI6IjA1MzgqKio3NSoqIiwiaXNzIjoidGVzdC5jb20iLCJleHAiOjE2NDkyNTM5ODcsImp0aSI6InJlZnJlc2hfdG9rZW4ifQ.SbLRBFCjaePFu8kjmYRrBfj6iHWBJoLzABwD2d8vxIQlEM2ZZXzJ9wUCu_MiIZ7B6M5k4aRtjdg4TDEJ3HvwnAQMl63P5C46iKaDmmhg4-hx0M_alwo8f5iDuQ2BAInPiPVo4qjFQQqN_Yti0qfW2amGGwvA5yTXK1D4NONR6B7CPY1SrqPgnZ9Q2zZv039SxbsdQTtZ2u80sA2b8kmAoK69NZt6PadSFRjdXy-VMzuG5HitSvtP4xLplFGfvptHg0DrNeGEy4daqofbBXYybPbPi0VQ3mxSjYaK2EIOFOm2FJDISQ_7sZXy6pwOYepKR5CfNAzRskM_Tpf6G2Nt9g

CodePudding user response:

The problem is in this line:

return decodedJWT.getClaims().entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, x -> x.getValue().toString()));

The dictionary values are Claim instances and Claim instances are basically pieces of JSON, so they can be a number, a string, an array or a dictionary.

If the generic toString() method is called, the result is formatted such that the the type can be safely distinguished, e.g.:

  • 37 for a number
  • " 1231551921" for a string
  • [ 37, " 1231551921" ] for an array

It you are sure that your claim is of type string, call asString() instead of toString().

  • Related