覆盖 JWT OAuth 令牌的 UserAuthenticationConverter [英] Override UserAuthenticationConverter for JWT OAuth Tokens

查看:38
本文介绍了覆盖 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 时,它们都为空.我已将资源服务器配置为使用 JWK 密钥集 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆