Spring Framework - Where to parse JWT for custom claim?

dplesa picture dplesa · Jul 21, 2017 · Viewed 13.7k times · Source

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?

Answer

Chillz picture Chillz · Aug 7, 2017

You can use a combination of a Jackson Object Mapper and Spring Security classes, namely Jwt, JwtHelper and Authentication. You can get the authentication by using Spring Security's static context object and then parse the token you receive using the JwtHelper.

ObjectMapper objectMapper = new ObjectMapper();
Authentication authentication = 
SecurityContextHolder.getContext().getAuthentication();
Map<String, Object> map = 
objectMapper.convertValue(authentication.getDetails(), Map.class);

// create a token object to represent the token that is in use.
Jwt jwt = JwtHelper.decode((String) map.get("tokenValue"));

// jwt.getClaims() will return a JSON object of all the claims in your token
// Convert claims JSON object into a Map so we can get the value of a field
Map<String, Object> claims = objectMapper.readValue(jwt.getClaims(), Map.class);
String customField = (String) claims.get("you_custom_field_name");

I would suggest debugging and putting a breakpoint on the third line in the code above. At that point, expose the authentication object. I might have some useful details you'll need later.

This can all be done on the controller. I'm not sure how to use the filter to do so.