Auth2 server 自定义 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;
}
自定义MyOAuth2Authentication保存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
通过以下办法,获取的Authentication,就是自定义的MyOAuth2Authentication,这样就可以获取到在token中保存的org属性。
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if(auth instanceof MyOAuth2Authentication){
System.out.println("/"+((MyOAuth2Authentication)auth).getOrg());
}
参考文章 https://github.com/ameizi/spring-boot-oauth2-example