6

我无法从 keycloak 生成的访问令牌中提取用户信息。我有一个受保护的路由,我期望正确填充 Principal 或 Authentication 对象。

@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {

    private final String SIGNING_KEY = "MIIBCgKCAQ...AB";

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http
                .requestMatcher(new RequestHeaderRequestMatcher("Authorization"))
                .authorizeRequests()
                .antMatchers("/api/register").anonymous()
                .antMatchers("/api/token").anonymous()
                .anyRequest().authenticated();
    }

    @Override
    public void configure(ResourceServerSecurityConfigurer config) {
        config.tokenServices(createTokenServices());
    }

    @Bean
    @Primary
    public DefaultTokenServices createTokenServices() {
        DefaultTokenServices defaultTokenServices = new DefaultTokenServices();
        defaultTokenServices.setTokenStore(createTokenStore());
        return defaultTokenServices;
    }

    @Bean
    public TokenStore createTokenStore() {
        return new JwtTokenStore(createJwtAccessTokenConverter());
    }

    @Bean
    public JwtAccessTokenConverter createJwtAccessTokenConverter() {
        JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
        converter.setAccessTokenConverter(new JwtConverter());
//        converter.setSigningKey(SIGNING_KEY);
        return converter;
    }

    public static class JwtConverter extends DefaultAccessTokenConverter implements JwtAccessTokenConverterConfigurer {

        @Override
        public void configure(JwtAccessTokenConverter converter) {
            converter.setAccessTokenConverter(this);
        }

        @Override
        public OAuth2Authentication extractAuthentication(Map<String, ?> map) {
            OAuth2Authentication auth = super.extractAuthentication(map);
            auth.setDetails(map); //this will get spring to copy JWT content into Authentication
            return auth;
        }
    }
}

在 Profile 控制器中,我想显示传入令牌的详细信息。

    @GetMapping("/api/profile/details")
    public Object details(final Principal authentication) {

//        Object details = authentication.getDetails();
//        if (details instanceof OAuth2AuthenticationDetails) {
//            OAuth2AuthenticationDetails oAuth2AuthenticationDetails = (OAuth2AuthenticationDetails) details;
//            Map<String, Object> decodedDetails = (Map<String, Object>) oAuth2AuthenticationDetails.getDecodedDetails();
//
//            return decodedDetails;
//        }

        return authentication.getName();
    }

调用上述端点时出现以下错误。

{
    "error": "invalid_token",
    "error_description": "Cannot convert access token to JSON"
}

无论我是否传递签名密钥都没有区别。

感谢您的帮助。

4

0 回答 0