th令牌的UserAuthenticationConverter

th令牌的UserAuthenticationConverter

本文介绍了覆盖JWT OAuth令牌的UserAuthenticationConverter的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

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

I am trying to create a spring resource server secured with oauth2.

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

I am using auth0 for my auth2 service, and I have an api and client configured with scopes.

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

I have a resource server that mostly works. It is secured, and I can use @EnableGlobalMethodSecurity and @PreAuthorize("#oauth2.hasScope('profile:read')") to limit access to tokens with that scope.

但是,当我尝试获取Principal或OAuth2Authentication时,它们都为null.我已将资源服务器配置为使用JWK key-set-uri.

However, when I try to get the Principal or the OAuth2Authentication they are both null. I've configured the resource server to use the JWK key-set-uri.

我怀疑这与DefaultUserAuthenticationConverter试图读取JWT的'user_name'声明有关,但是它需要从'sub'声明中读取它,而且我不知道如何更改此设置行为.

I suspect that this has to do with the DefaultUserAuthenticationConverter trying to read the the 'user_name' claim form the JWT, but it needs to be reading it from the 'sub' claim, and I don't know how to change this behaviour.

推荐答案

首先创建一个UserAuthenticationConverter:

First create a 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;
    }
}

然后配置spring使其像这样使用:

Then configure spring to use it like so:

@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);
    }
}

这篇关于覆盖JWT OAuth令牌的UserAuthenticationConverter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 16:18