Springboot和Oauth2:TokenEnhancer无法正常工作到不同的对象

时间:2019-06-28 08:26:58

标签: java spring-boot oauth-2.0

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 我得到用户对象只是想知道为什么会这样。我认为无论Grant_type如何,它都应该始终返回相同的对象 也欢迎任何好的解释。

0 个答案:

没有答案