Spring Framework - 在哪里解析JWT以获取自定义声明?

时间:2017-07-21 07:07:34

标签: spring spring-security jwt spring-security-oauth2

我创建了一个Spring JWT授权应用程序。 JWT包含一些自定义声明。在资源服务器端,我想知道,我应该在哪里解析JWT令牌来收集和检查这些声明?我应该在控制器或某个过滤器中执行此操作吗?什么是最佳做法?也许你有一些例子?

3 个答案:

答案 0 :(得分:6)

您可以结合使用Jackson Object Mapper和Spring Security类,即Jwt,JwtHelper和Authentication。您可以使用Spring Security的静态上下文对象获取身份验证,然后使用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");

我建议在上面代码的第三行调试并设置一个断点。此时,公开身份验证对象。我可能会在稍后提供一些有用的细节。

这一切都可以在控制器上完成。我不确定如何使用过滤器。

答案 1 :(得分:2)

你也可以使用springframework.boot.json.JsonParser:

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

> tokenData.get("VALID_KEY");

答案 2 :(得分:0)

我正在使用它:

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) {
        ex.printStackTrace();
        return null;
    }
}