【发布时间】:2018-11-03 13:59:31
【问题描述】:
您好,我曾尝试在 Spring Boot 中使用 jwt 令牌,但遇到了将自定义声明添加到 jwt 令牌中的问题。我想添加自定义声明,例如 issuer、audience、exp、sub、...user:{}、.. 如何将我的对象添加到标题和有效负载部分
【问题讨论】:
标签: spring-mvc spring-boot jwt spring-security-oauth2
您好,我曾尝试在 Spring Boot 中使用 jwt 令牌,但遇到了将自定义声明添加到 jwt 令牌中的问题。我想添加自定义声明,例如 issuer、audience、exp、sub、...user:{}、.. 如何将我的对象添加到标题和有效负载部分
【问题讨论】:
标签: spring-mvc spring-boot jwt spring-security-oauth2
我假设您使用的是 spring-security-oauth2。我没有得到How can I add my object into header and payload sections 的部分,但您可以使用TokenEnhancer 提到的in this tutorial。该教程中的示例 sn-p 如下所示:
public class CustomTokenEnhancer implements TokenEnhancer {
@Override
public OAuth2AccessToken enhance(
OAuth2AccessToken accessToken,
OAuth2Authentication authentication) {
Map<String, Object> additionalInfo = new HashMap<>();
additionalInfo.put("organization", authentication.getName() + randomAlphabetic(4));
((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInfo);
return accessToken;
}
}
要获取更多信息,您可以使用 AuthorizationServerTokenServices
tokenServices.getAccessToken(authentication).getAdditionalInformation();
【讨论】:
我已经用下面的代码解决了:
@Bean
public JwtAccessTokenConverter tokenEnhancer() {
KeyStoreKeyFactory keyStoreKeyFactory = new KeyStoreKeyFactory(
new ClassPathResource("jwt.jks"),
keyStorePassword.toCharArray());
// For getting user information in getPrincipal()
DefaultUserAuthenticationConverter duac = new DefaultUserAuthenticationConverter();
duac.setUserDetailsService(userDetailsService);
DefaultAccessTokenConverter datc = new DefaultAccessTokenConverter();
datc.setUserTokenConverter(duac);
JwtAccessTokenConverter converter = new CustomAccessTokenConverter();
converter.setAccessTokenConverter(datc); // IMPORTANT
converter.setKeyPair(keyStoreKeyFactory.getKeyPair("jwt"));
return converter;
}
【讨论】: