can I include user information while issuing an access token?

后端 未结 6 660
無奈伤痛
無奈伤痛 2020-11-28 03:58

I have seen in some oauth2 implementations additional information on the response returned by the authorization server when it issues access tokens. I\'m wondering if there

6条回答
  •  旧巷少年郎
    2020-11-28 04:43

    1. create a class file CustomTokenEnhancer
    @Component
    public class CustomTokenConverter extends JwtAccessTokenConverter {
    
    
        @Override
        public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
    
            final Map additionalInfo = new HashMap<>();
            additionalInfo.put("customized", "true");
            User user = (User) authentication.getPrincipal();
            additionalInfo.put("role", user.getAuthorities().stream().map(GrantedAuthority::getAuthority).collect(Collectors.toList()));
            ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInfo);
    
            return super.enhance(accessToken, authentication);
        }
    }
    
    1. paste below written code in AuthorizationServerConfig
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        TokenEnhancerChain enhancerChain = new TokenEnhancerChain();
        enhancerChain.setTokenEnhancers(Arrays.asList(customTokenEnhancer(),accessTokenConverter()));
    
        endpoints
            .tokenStore(tokenStore())
            .tokenEnhancer(customTokenEnhancer())
            .authenticationManager(authenticationManager);
    }
    
    @Bean
    protected JwtAccessTokenConverter jwtTokenEnhancer() {
        JwtAccessTokenConverter converter=  new JwtAccessTokenConverter();
        converter.setSigningKey("my_signing_key");
    
        return converter;
    }
    
    @Bean
    public CustomTokenConverter customTokenEnhancer() {
        return new CustomTokenConverter();
    }
    
    @Bean
    public TokenStore tokenStore() {
        return new JdbcTokenStore(dataSource);
    }
    
    1. import appropriate libraries after paste the above codes

    output response of Custom Token Enhancer..click here

提交回复
热议问题