如何从资源服务器中的Spring Security OAuth2 Boot 中提取声明?

9jyewag0  于 2022-11-24  发布在  Spring
关注(0)|答案(1)|浏览(174)

我在.Net Core中内置了一个Authorization Server,使用Identity Server 4!它可以按预期工作,对来自Node Js和. Net的客户端和资源进行授权。现在,我尝试添加Java Sping Boot 2 API(jdk1.8)作为受保护的资源。我已经通过使用OAuth2 Boot 文档实现了这个目标!到目前为止一切都工作正常。现在,我需要从授权服务器生成的访问令牌中提取声明。这是一个类型为JWT的承载令牌。我的实现如下:

@Configuration
@EnableResourceServer
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfiguration extends ResourceServerConfigurerAdapter {
  public String resourceId;

  @Autowired
  public SecurityConfiguration(@Value("${security.oauth2.resource.id}") String resourceId) {
    this.resourceId = resourceId;
  }

@Override
  public void configure(ResourceServerSecurityConfigurer resources) {
    resources.resourceId(this.resourceId);
}

  @Override
  public void configure(HttpSecurity httpSecurity) throws Exception {
    httpSecurity
        .csrf()
        .disable()
        .authorizeRequests()
        .antMatchers("/swagger-ui.html", "/webjars/**", "/swagger-resources/**", "/**/api-docs/**", "/actuator/**")
        .permitAll()
        .and()
        .authorizeRequests().anyRequest().fullyAuthenticated();
  }

问题是,当我试图访问控制器中的声明时,它们不可用。我已经检查了spring security中DefaultAccessTokenConverter的默认extractAuthentication方法,它确实忽略了所有非默认声明。我的想法是创建一个新的转换器来扩展DefaultAccessToken转换器,如下所示:

@Component
public class CustomAccessTokenConverter extends DefaultAccessTokenConverter {

  @Override
  public OAuth2Authentication extractAuthentication(Map<String, ?> claims) {
    OAuth2Authentication authentication = super.extractAuthentication(claims);
    authentication.setDetails(claims);
    return authentication;
  }
}

但是我还没有弄清楚在哪里注入或引用这个新的转换器。

ev7lccsx

ev7lccsx1#

不幸的是,Spring Boot auto-configuration似乎没有提供替换DefaultAccessTokenConverter的方法,DefaultAccessTokenConverterRemoteTokenServices中的默认令牌转换器。要替换该转换器,必须替换默认创建的RemoteTokenServices
如果您的转换器是一个bean,您可以在您自己的RemoteTokenServices对象上设置它,然后再在ResourceServerSecurityConfigurer上设置它(这样它就可以在后台应用于OAuth2AuthenticationManager):

@Configuration
@EnableResourceServer
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfiguration extends ResourceServerConfigurerAdapter {
    // ...

    @Autowired
    private ResourceServerProperties resource;

    @Autowired
    private CustomAccessTokenConverter customConverter;

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) {
        resources.tokenServices(customTokenServices());
        // ..
    }

    private RemoteTokenServices customTokenServices() {
        RemoteTokenServices services = new RemoteTokenServices();
        services.setAccessTokenConverter(this.customConverter);

        // configure based on .properties file 
        services.setCheckTokenEndpointUrl(this.resource.getTokenInfoUri());
        services.setClientId(this.resource.getClientId());
        services.setClientSecret(this.resource.getClientSecret());

        return services;
    }

    // ..

相关问题