Spring security oauth2 重写JWT OAuth令牌的UserAuthenticationConverter

Spring security oauth2 重写JWT OAuth令牌的UserAuthenticationConverter,spring-security-oauth2,auth0,Spring Security Oauth2,Auth0,我正在尝试创建一个用oauth2保护的spring资源服务器 我将auth0用于auth2服务,我有一个配置了作用域的api和客户端 我有一个主要工作的资源服务器。它是安全的,我可以使用@EnableGlobalMethodSecurity和@PreAuthorize(#oauth2.hasScope('profile:read'))来限制对该范围内令牌的访问 但是,当我尝试获取主体或OAuth2Authentication时,它们都是空的。我已经将资源服务器配置为使用JWK密钥集uri 我怀疑

我正在尝试创建一个用oauth2保护的spring资源服务器

我将auth0用于auth2服务,我有一个配置了作用域的api和客户端

我有一个主要工作的资源服务器。它是安全的,我可以使用@EnableGlobalMethodSecurity和@PreAuthorize(#oauth2.hasScope('profile:read'))来限制对该范围内令牌的访问

但是,当我尝试获取主体或OAuth2Authentication时,它们都是空的。我已经将资源服务器配置为使用JWK密钥集uri


我怀疑这与DefaultUserAuthenticationConverter试图从JWT中读取“用户名”声明有关,但它需要从“子”声明中读取,我不知道如何更改此行为。

首先创建UserAuthenticationConverter:

public class OidcUserAuthenticationConverter implements UserAuthenticationConverter {

    final String SUB = "sub";

    @Override
    public Map<String, ?> convertUserAuthentication(Authentication userAuthentication) {
        throw new UnsupportedOperationException();
    }

    @Override
    public Authentication extractAuthentication(Map<String, ?> map) {
        if (map.containsKey(SUB)) {
            Object principal = map.get(SUB);
            Collection<? extends GrantedAuthority> authorities = null;
            return new UsernamePasswordAuthenticationToken(principal, "N/A", authorities);
        }
        return null;
    }
}
@Configuration
public class OidcJwkTokenStoreConfiguration {
    private final ResourceServerProperties resource;

    public OidcJwkTokenStoreConfiguration(ResourceServerProperties resource) {
        this.resource = resource;
    }

    @Bean
    public TokenStore jwkTokenStore() {
        DefaultAccessTokenConverter tokenConverter = new DefaultAccessTokenConverter();
        tokenConverter.setUserTokenConverter(new OidcUserAuthenticationConverter());
        return new JwkTokenStore(this.resource.getJwk().getKeySetUri(), tokenConverter);
    }
}