Springboot и Oauth2: TokenEnhancer не работает должным образом, попал в разные объекты - PullRequest
0 голосов
/ 28 июня 2019

Springboot версия 2.1.4 Пружина безопасности oauth2 версия 2.3.5

Я пытаюсь добавить пользовательский TokenEnhancer, чтобы добавить дополнительную информацию с ответом токена. Я получаю необходимые детали, но сталкиваюсь со странной проблемой. Вот мой код

@Configuration
@EnableAuthorizationServer
public class OAuthConfiguration extends AuthorizationServerConfigurerAdapter {
    private static final Logger logger = LogManager.getLogger(OAuthConfiguration.class);

    @Value("${oauth2.client.id}")
    private String clientId;

    @Value("${oauth2.client.secret}")
    private String clientSecret;

    @Value("${oauth2.token.accessValidity}")
    private int accessValidity;

    @Value("${oauth2.token.refreshValidity}")
    private int refreshValidity;

    @Autowired
    private UserService userService;

    @Autowired
    private AuthenticationManager authenticationManager;

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {

        clients.inMemory()
                .withClient(clientId)
                .secret(passwordEncoder().encode(clientSecret))
                .authorizedGrantTypes("password", "refresh_token")
                .accessTokenValiditySeconds(accessValidity)
                .refreshTokenValiditySeconds(refreshValidity);
    }

    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) {
        security.passwordEncoder(passwordEncoder())
                .allowFormAuthenticationForClients()
                .tokenKeyAccess("permitAll()")
                .checkTokenAccess("isAuthenticated()");

        CorsConfiguration config = new CorsConfiguration();
        config.applyPermitDefaultValues();

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", config);

        CorsFilter filter = new CorsFilter(source);
        security.addTokenEndpointAuthenticationFilter(filter);
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
        endpoints.requestValidator(new RequestValidator())
                .pathMapping("/oauth/token", "/token")
                .pathMapping("/oauth/check_token", "/check_token")
                .tokenStore(tokenStore())
                .authenticationManager(authenticationManager)
                .userDetailsService(userService)
                .tokenEnhancer(accessTokenEnhancer());
    }

    @Bean
    public TokenStore tokenStore() {
        return new InMemoryTokenStore();
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return NoOpPasswordEncoder.getInstance();
    }

    @Bean
    public TokenEnhancer accessTokenEnhancer() {
        ChecksumTokenEnhancer enhancer = new ChecksumTokenEnhancer();
        return enhancer;
    }


    private class ChecksumTokenEnhancer implements TokenEnhancer {
        @Override
        public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
            final String user = authentication.getPrincipal() instanceof User ? ((User) authentication.getPrincipal()).getUsername() : authentication.getPrincipal().toString() ;
            final Map<String, Object> additionalInfo = new HashMap<>();
            try {
                additionalInfo.put("checksum",user);
            } catch (Exception e) {
                logger.error(e);
            }
            ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInfo);
            return accessToken;
        }
    }
}

Как вы можете видеть в строке

final String user = authentication.getPrincipal() instanceof User ? ((User) authentication.getPrincipal()).getUsername() : authentication.getPrincipal().toString() ;

Я получаю разные результаты, когда звоню http://localhost:8080/security/token?grant_type=password Я получил простую строку, обернутую в объект, и когда я звоню http://localhost:8080/security/token?grant_type=refresh_token Я получил User Object просто хотел знать, почему это так. Я думаю, что он должен возвращать один и тот же объект все время, независимо от grant_type Любое хорошее объяснение также приветствуется.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...