具有OAuth2的Spring Resource Server中继访问令牌

问题描述

我有一个受OAuth2(KeyCloak)保护的Spring Boot资源服务器。我可以使用Bearer Token访问端点。现在,我想调用由Auth Server保护的另一项服务。我想中继令牌。我找不到有关如何执行操作的明确指南。

我的依赖项是:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-oauth2-resource-server</artifactId>
</dependency>

我的application.yml就像:

spring:
  security:
    oauth2:
      resourceserver:
        jwt:
          issuer-uri: <info>

我正在尝试创建OAuth2RestTemplate,例如:

    @Bean
    public OAuth2RestTemplate oauth2RestTemplate(OAuth2ClientContext oauth2ClientContext,OAuth2ProtectedResourceDetails details) {
        return new OAuth2RestTemplate(details,oauth2ClientContext);
    }   

但是我遇到了错误:

required a bean of type 'org.springframework.security.oauth2.client.resource.OAuth2ProtectedResourceDetails' that could not be found.

我该如何解决?

解决方法

经过大量研究和反复试验,得出的解决方案是:

添加依赖项

        <dependency>
            <groupId>org.springframework.security.oauth.boot</groupId>
            <artifactId>spring-security-oauth2-autoconfigure</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-jwt</artifactId>
            <version>1.1.1.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-oauth2-resource-server</artifactId>
        </dependency>

@EnableOAuth2Client

在application.yml中,我同意了

security:
  oauth2:
    keycloak:
      clientId: <CLIENT_ID>
      clientSecret: <CLIENT_SECRET>
      grantType: client_credentials
      accessTokenUri: <URI>
      userAuthorizationUri: <URI>
      scope: openid profile email

配置


    @Bean
    @ConfigurationProperties("security.oauth2.keycloak")
    protected OAuth2ProtectedResourceDetails keycloakOAuth2Details() {
        return new ClientCredentialsResourceDetails();
    }

    
    @LoadBalanced
    @Bean
    public OAuth2RestTemplate restTemplate(RestTemplateCustomizer customizer) {
        OAuth2RestTemplate restTemplate = new OAuth2RestTemplate(keycloakOAuth2Details);
        customizer.customize(restTemplate);
        return restTemplate;
    }

我不确定这是否有必要。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...