oauth-2.0 - Spring sercurity中的自定义JWT响应
问题描述
我使用 API oauth/token 在 spring sercurity oauth2 中获取 JWT 令牌。我尝试通过使用 TokenEnhancer 接口的增强方法 ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInfo) 在响应中添加一些附加信息。但是这些附加信息也添加到了 JWT 中,所以它太大了。有没有办法将附加信息添加到 oauth/token 请求的正文中,但不是在 JWT 中。
@Override
public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
final Map<String, Object> additionalInfo = new HashMap<>();
WebUser webUser = (WebUser) authentication.getUserAuthentication().getPrincipal();
additionalInfo.put("user_name", authentication.getName());
additionalInfo.put("roles", authentication.getAuthorities());
if(webUser.getFunctions() != null) {
additionalInfo.put("functions", webUser.getFunctions().toString());
}else {
additionalInfo.put("functions", null);
}
((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInfo);
return accessToken;
}
解决方案
当您修改令牌时,在 Spring 上下文中称为“增强令牌”。从逻辑上讲,您应该首先将令牌转换为 JWT,然后添加其他属性,这样它们就不会影响您的 JWT 有效负载。
这是我使用 Spring Boot 构建的项目中的一个片段
@Override
public void configure(final AuthorizationServerEndpointsConfigurer endpoints) {
TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();
tokenEnhancerChain.setTokenEnhancers(
Arrays.asList(tokenEnhancer(), jwtAccessTokenConverter()));
endpoints.authenticationManager(authenticationManager)
.userDetailsService(userDetailsService)
.tokenEnhancer(tokenEnhancerChain)
.accessTokenConverter(jwtAccessTokenConverter())
.tokenStore(tokenStore());
}
在这里,我使用tokenEnhancer()
向我的令牌添加了一些属性,然后使用jwtAccessTokenEnhancer()
. 如果我在这里颠倒顺序,我会得到你想要的。
推荐阅读
- git - 如何使用 git 仅授予对部分 repo 的访问权限?
- php - 这个sql查询怎么注入?
- javascript - React Native 性能:Javascript 与 Typescript
- reactjs - 如何在不安装表单的情况下在 React 中发起发布请求?
- angular - Angular Material 表数据源问题
- ios - 在后台执行 Apple 快捷方式
- docker - 如何让前端 Docker 容器找到后端容器 ip?
- dart - 在 Dart 中解析动态数据
- javascript - 如何使用 post 方法或在 javascript 中获取发送的数据
- .net - 如何避免在.NET中传递值类型参数时的装箱?