Spring Framework - 在哪里解析 JWT 以获取自定义声明? [英] Spring Framework - Where to parse JWT for custom claim?

查看:35
本文介绍了Spring Framework - 在哪里解析 JWT 以获取自定义声明?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

推荐答案

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

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.

这篇关于Spring Framework - 在哪里解析 JWT 以获取自定义声明?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆