Auth2 server custom TokenEnhancer
1------------
public class CustomTokenEnhancer implements TokenEnhancer {
@Override
public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
final Map<String, Object> additionalInfo = new HashMap<>();
additionalInfo.put("organization", "RandomORG");
((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInfo);
System.out.println(".........."+accessToken);
return accessToken;
}
}
2---------------
@Bean
public TokenEnhancer tokenEnhancer () {
return new CustomTokenEnhancer ();
}
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();
tokenEnhancerChain.setTokenEnhancers(
Arrays.asList(
tokenEnhancer()
,
accessTokenConverter()
)
);
//
endpoints.tokenStore(tokenStore())
.tokenEnhancer(tokenEnhancerChain)
.authenticationManager(authenticationManager);
}
3-resource server
@Component
public class MyJwtAccessTokenConverter extends JwtAccessTokenConverter{
@Override
public OAuth2Authentication extractAuthentication(Map<String, ?> map) {
OAuth2Authentication auth2Authentication = getAccessTokenConverter().extractAuthentication(map);
MyOAuth2Authentication myOAuth2Authentication = new MyOAuth2Authentication(auth2Authentication.getOAuth2Request(),auth2Authentication.getUserAuthentication());
myOAuth2Authentication.setOrg((String)map.get("organization"));
//convert to my Authentication, I add some information here..
return myOAuth2Authentication;
}
}
@Bean
@Primary
protected JwtAccessTokenConverter jwtTokenEnhancer() {
MyJwtAccessTokenConverter converter = new MyJwtAccessTokenConverter();
//option 1
Resource resource = new ClassPathResource("public.cert");
String publicKey = null;
try {
publicKey = new String(FileCopyUtils.copyToByteArray(resource.getInputStream()));
} catch (IOException e) {
throw new RuntimeException(e);
}
converter.setVerifierKey(publicKey);
//option 2
//converter.setSigningKey("123");
return converter;
}
Custom MyOAuth2Authentication saves the extra attributes added by the token
public class MyOAuth2Authentication extends OAuth2Authentication{
/**
*
*/
private static final long serialVersionUID = 7383757097967991480L;
private String org;
public MyOAuth2Authentication(OAuth2Request storedRequest, Authentication userAuthentication) {
super(storedRequest, userAuthentication);
}
。。。
END
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!11
Through the following methods, the obtained Authentication is the custom MyOAuth2Authentication, so that the org attribute saved in the token can be obtained.
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if(auth instanceof MyOAuth2Authentication){
System.out.println("/////"+((MyOAuth2Authentication)auth).getOrg());
}
Reference article https://github.com/ameizi/spring-boot-oauth2-example