Spring Framework - Where to parse JWT for custom claim?

Viewed 22281

I have created a Spring JWT authorization application. JWT contains some custom claims. On a resource server side, I wonder, where should I parse the JWT token to collect and check these claims? Should I do this in a controller or in some filter? Whats the best practice? Maybe you have some example?

3 Answers

you can also use springframework.boot.json.JsonParser:

JsonParser parser = JsonParserFactory.getJsonParser();
Map<String, ?> tokenData = parser.parseMap(JwtHelper.decode(token).getClaims());

> tokenData.get("VALID_KEY");

I'm using this:

private Claim getClaim(String claimKey) {
    Authentication token = SecurityContextHolder.getContext().getAuthentication();
    try {
        DecodedJWT jwt = JWT.decode(token.getCredentials().toString());
        return jwt.getClaim(claimKey);
    } catch (JWTVerificationException ex) {
        throw new RuntimeException(ex);
    }
}
Related