I'm working in a project apply Spring boot and JWT. In OAuth2 configuration, I added more information into JWT sucessfully but I don't know how to extract this information when process a request contained my information.
Below is the code segment with I added my additional information:
public class CustomTokenEnhancer implements TokenEnhancer {
@Override
public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
Map<String, Object> additionalInfo = new HashMap<>();
additionalInfo.put("user_name", authentication.getName());
User user = userService().getUserDetailsByLoginId(authentication.getName());
additionalInfo.put("user_id", user.getRelationPartId());
((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInfo);
return accessToken;
}
}
If you had experienced on it, please help me to get user_id from my token when process a request.
Thanks
Finally, I got a solution, it works like a champ... Below is some code segment, hope it help...
@Bean
public TokenStore tokenStore() {
return new JwtTokenStore(accessTokenConverter());
}
@Bean
public TokenEnhancer customTokenEnhancer() {
return new CustomTokenEnhancer();
}
@Bean
public DefaultAccessTokenConverter customAccessTokenConverter() {
return new DefaultAccessTokenConverter();
}
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();
tokenEnhancerChain.setTokenEnhancers(Arrays.asList(customTokenEnhancer(), accessTokenConverter()));
endpoints.tokenStore(tokenStore()).tokenEnhancer(tokenEnhancerChain)
.accessTokenConverter(customAccessTokenConverter())
.authenticationManager(authenticationManager);
}
In Controller:
@Autowired
private TokenStore tokenStore;
@ApiOperation(value = "test get security data", response = String.class)
@RequestMapping(value = "/getUser1", method = RequestMethod.GET)
public @ResponseBody String getData1(OAuth2Authentication principal) {
OAuth2AuthenticationDetails auth2AuthenticationDetails = (OAuth2AuthenticationDetails) principal.getDetails();
Map<String, Object> details = tokenStore.readAccessToken(auth2AuthenticationDetails.getTokenValue()).getAdditionalInformation();
String department= (String) details.get("department");
return null;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.