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

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

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

最佳答案

您可以结合使用 Jackson Object Mapper 和 Spring Security 类,即 Jwt、JwtHelper 和 Authentication。您可以使用 Spring Security 的静态上下文对象获取身份验证,然后使用 JwtHelper 解析您收到的 token 。

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");

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

这一切都可以在 Controller 上完成。我不确定如何使用过滤器来做到这一点。

关于Spring Framework - 在哪里解析 JWT 以进行自定义声明?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45231203/

相关文章:

java - Spring @Inject 服务类返回空指针异常

java - NoSuchBeanDefinitionException : No qualifying bean of type for inner class

java - Spring安全身份验证问题: HTTP 401

php - 使用 JWT 缺少授权 header

python - JWT 如何与 django-phonenumber-field 一起工作

java - 如何在spring中使用java配置设置bean

Spring5.0.1 VelocityEngineFactoryBean

grails - Grails应用程序未与过滤器一起运行

grails - 如何使用IS_AUTHENTICATED_FULLY IN grails 3 spring-security

jwt - 如何将 OpenIdconnect 与 istio 集成?