can I include user information while issuing an access token?

后端 未结 6 659
無奈伤痛
無奈伤痛 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:28

    You will need to implement a custom TokenEnhancer like so:

    public class CustomTokenEnhancer implements TokenEnhancer {
    
        @Override
        public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
            User user = (User) authentication.getPrincipal();
            final Map additionalInfo = new HashMap<>();
    
            additionalInfo.put("customInfo", "some_stuff_here");
            additionalInfo.put("authorities", user.getAuthorities());
    
            ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInfo);
    
            return accessToken;
        }
    
    }
    

    and add it to your AuthorizationServerConfigurerAdapter as a bean with the corresponding setters

    @Configuration
    @EnableAuthorizationServer
    protected static class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {
    
        // Some autowired stuff here
    
        @Override
        public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
            // @formatter:off
            endpoints
                // ...
                .tokenEnhancer(tokenEnhancer());
            // @formatter:on
        }
    
        @Bean
        @Primary
        public AuthorizationServerTokenServices tokenServices() {
            DefaultTokenServices tokenServices = new DefaultTokenServices();
            // ...
            tokenServices.setTokenEnhancer(tokenEnhancer());
            return tokenServices;
        }
    
        // Some @Bean here like tokenStore
    
        @Bean
        public TokenEnhancer tokenEnhancer() {
            return new CustomTokenEnhancer();
        }
    
    }
    

    then in a controller (for example)

    @RestController
    public class MyController {
    
        @Autowired
        private AuthorizationServerTokenServices tokenServices;
    
        @RequestMapping(value = "/getSomething", method = RequestMethod.GET)
        public String getSection(OAuth2Authentication authentication) {
            Map additionalInfo = tokenServices.getAccessToken(authentication).getAdditionalInformation();
    
            String customInfo = (String) additionalInfo.get("customInfo");
            Collection authorities = (Collection) additionalInfo.get("authorities");
    
            // Play with authorities
    
            return customInfo;
        }
    
    }
    

    I'm personnaly using a JDBC TokenStore so my "Some autowired stuff here" are corresponding to some @Autowired Datasource, PasswordEncoder and what not.

    Hope this helped!

提交回复
热议问题