您好我曾尝试在spring boot中使用jwt令牌,但我遇到了将自定义声明添加到jwt令牌中的问题。我想添加自定义声明,如发行者,观众,exp,sub,... user:{},.. 如何将我的对象添加到标题和有效负载部分
答案 0 :(得分:1)
我假设你使用的是spring-security-oauth2。我没有收到How can I add my object into header and payload sections
部分,但您可以使用TokenEnhancer in this tutorial。该教程的示例片段如下所示:
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();
答案 1 :(得分:-1)
我已通过以下代码解决了该问题:
@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;
}