Spring框架-在哪里解析JWT以进行自定义声明?

2024-02-25

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


您可以结合使用 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");

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

这一切都可以在控制器上完成。我不知道如何使用过滤器来做到这一点。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Spring框架-在哪里解析JWT以进行自定义声明? 的相关文章

随机推荐