oauth 2.0 JWT 默认返回 OAuth2AccessToken 接口的实现类,默认实现类是 DefaultOAuth2AccessToken,返回字段有 5 个
TokenEhancer
实现 TokenEhancer(令牌增强器)接口
@Bean
public TokenEnhancer customTokenEnhancer() {
return (accessToken, authentication) -> {
final Map<String, Object> additionalInfo = new HashMap<>();
additionalInfo.put("fat", "test");
((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInfo);
return accessToken;
};
}
AuthorizationServerEndpointsConfigurer
把 TokenEnhancer 添加到 AuthorizationServerConfigurerAdapter 里
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
...
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
TokenEnhancerChain enhancerChain = new TokenEnhancerChain();
enhancerChain.setTokenEnhancers(Arrays.asList(jwtAccessTokenConverter(), customTokenEnhancer()));
DefaultTokenServices tokenServices = new DefaultTokenServices();
tokenServices.setTokenEnhancer(enhancerChain);
tokenServices.setTokenStore(tokenStore());
endpoints
.authenticationManager(authenticationManager)
.tokenServices(tokenServices)
;
}
...
}
访问 /oauth/token 接口时,返回值返回插入的 fat 字段
JWT 解析发现没有 fat 字段
**踩坑:**这里有一个值得注意的地方了,若要 JWT 解析时有新增字段,在 setTokenEnhancers 时,参数 list 需要把自定义的 customTokenEnhancer() 放前面
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
TokenEnhancerChain enhancerChain = new TokenEnhancerChain();
enhancerChain.setTokenEnhancers(Arrays.asList(customTokenEnhancer(), jwtAccessTokenConverter()));
DefaultTokenServices tokenServices = new DefaultTokenServices();
tokenServices.setTokenEnhancer(enhancerChain);
tokenServices.setTokenStore(tokenStore());
endpoints
.authenticationManager(authenticationManager)
.tokenServices(tokenServices)
;
}
自定义 AccessTokenConverter
@Configuration
public class AuthAccessTokenConverter extends DefaultAccessTokenConverter {
@Override
public Map<String, ?> convertAccessToken(OAuth2AccessToken token, OAuth2Authentication authentication) {
Map<String, Object> response = (Map<String, Object>) super.convertAccessToken(token, authentication);
response.put("feng","myfat");
return response;
}
}
把新建的 AccessTokenConverter 放进配置里
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
@Autowired
private AuthAccessTokenConverter converter;
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
...
endpoints.accessTokenConverter(converter);
}
}