考虑在配置中定义类型为'org.springframework.security.oauth2.client.registration.ReactiveClientRegistrationRepository'的bean。

我正在使用弹簧oAuthClient版本5.2.4.RELEASE通过遵循弹簧安全 https://docs.spring.io/spring-security/site/docs/current/reference/html5/#oauth2Client-authorized-manager-provider 的文档链接

    import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.oauth2.client.registration.ReactiveClientRegistrationRepository;
import org.springframework.security.oauth2.client.web.reactive.function.client.ServerOAuth2AuthorizedClientExchangeFilterFunction;
import org.springframework.security.oauth2.client.web.server.ServerOAuth2AuthorizedClientRepository;
import org.springframework.web.reactive.function.client.ExchangeFilterFunction;
import org.springframework.web.reactive.function.client.WebClient;

import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import reactor.core.publisher.Mono;

@AllArgsConstructor
@Configuration
@Slf4j
public class WebClientConfig {

    @Bean("AuthProvider")
    WebClient webClient(ReactiveClientRegistrationRepository clientRegistrations, ServerOAuth2AuthorizedClientRepository authorizedClients) {
        ServerOAuth2AuthorizedClientExchangeFilterFunction oauth = new ServerOAuth2AuthorizedClientExchangeFilterFunction(
                clientRegistrations,
                authorizedClients);
        oauth.setDefaultOAuth2AuthorizedClient(true);
        oauth.setDefaultClientRegistrationId("AuthProvider");
        return WebClient.builder()
                .filter(oauth)
                .filter(this.logRequest())
                .build();
    }


    private ExchangeFilterFunction logRequest() {
        return ExchangeFilterFunction.ofRequestProcessor(clientRequest -> {
            log.info("Request: [{}] {}", clientRequest.method(), clientRequest.url());
            log.debug("Payload: {}", clientRequest.body());
            return Mono.just(clientRequest);
        });
    }

application.yaml

   security:
    oauth2:
      client:
        provider:
          AuthProvider:
            token-uri: ${tokenpath<read from environment variable>}
        registration:
          AuthProvider:
            authorization-grant-type: client_credentials
            client-id: ${<read from environment variable>}
            client-secret: ${<read from environment variable>}

收到以下错误

    ***************************
APPLICATION FAILED TO START
***************************

Description:

Parameter 0 of method webClient in com.sample.config.WebClientConfig required a bean of type 'org.springframework.security.oauth2.client.registration.ReactiveClientRegistrationRepository' that could not be found.

The injection point has the following annotations:
    - @org.springframework.beans.factory.annotation.Autowired(required=true)


Action:

Consider defining a bean of type 'org.springframework.security.oauth2.client.registration.ReactiveClientRegistrationRepository' in your configuration.

让我知道,如果我错过了任何配置,因为没有从堆栈溢出的其他问题中获得任何特定的帮助


答案 1

我正在使用spring boot 2.3.1.RELEASE我遇到了同样的问题,我的pom.xml在我的pom中包含了这两个依赖项.xml

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-webflux</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

我删除了以下依赖项,这对我起作用了:

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

不是说这将解决您的麻烦,但这也可能是您的依赖关系冲突问题。

另一篇文章让我走上正轨:Reactive OAuth2 with Spring Security 5.3.2 ReactiveClientRegistration找不到存储库bean


答案 2

您的弹簧启动配置是完美的。


问题的根本原因:问题出在 application.yaml 中。配置错误或未从环境中选取。

因此,问题不在于 OAuth2 版本,而在于 application.yaml 中的配置。

注意:仅当您使用 OAuth2 应用程序所有者详细信息配置客户端时,才会创建 Bean。ReactiveClientRegistrationRepository


我从 start.spring.io 创建了一个新项目,并在其中使用了您的配置。

在使用您的配置运行项目后,我遇到了同样的问题。

错误日志 :

***************************
APPLICATION FAILED TO START
***************************

Description:

Parameter 0 of method webClient in com.example.sampleoauth2.WebClientConfig required a bean of type 'org.springframework.security.oauth2.client.registration.ReactiveClientRegistrationRepository' that could not be found.

The following candidates were found but could not be injected:
    - Bean method 'clientRegistrationRepository' in 'ReactiveOAuth2ClientConfigurations.ReactiveClientRegistrationRepositoryConfiguration' not loaded because OAuth2 Clients Configured Condition registered clients is not available


Action:

Consider revisiting the entries above or defining a bean of type 'org.springframework.security.oauth2.client.registration.ReactiveClientRegistrationRepository' in your configuration.

然后,我看到我没有在apprament.yml文件中配置属性。

我阅读了Spring Boot和OAuth2.0文档,介绍如何从github获取客户端ID和客户端密钥(示例),因为您将spring-boot应用程序注册为OAuth应用程序。

一旦我配置了我的应用程序开始工作。


我使用的是spring-boot 2.3.1.RELEASEOAuth2Client版本5.3.3

我的 pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.1.RELEASE</version>
        <relativePath /> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>sampleOauth2</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>sampleOauth2</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-oauth2-client</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-webflux</artifactId>
        </dependency>
        <dependency>
            <groupId>org.projectreactor</groupId>
            <artifactId>reactor-spring</artifactId>
            <version>1.0.1.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

我的客户端 github 注册属性的应用程序.yml

spring:
  security:
    oauth2:
      client:
        registration:
          github:
            client-id: 22a7100de41c7308d346
            client-secret: 05910ab890be29579e9c183443d92e756c450aaf

您更新的 WebClientConfig @Configuration类:

package com.example.sampleoauth2;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.oauth2.client.registration.ReactiveClientRegistrationRepository;
import org.springframework.security.oauth2.client.web.reactive.function.client.ServerOAuth2AuthorizedClientExchangeFilterFunction;
import org.springframework.security.oauth2.client.web.server.ServerOAuth2AuthorizedClientRepository;
import org.springframework.web.reactive.function.client.ExchangeFilterFunction;
import org.springframework.web.reactive.function.client.WebClient;

import reactor.core.publisher.Mono;

@Configuration
public class WebClientConfig {

    public static Logger log = LogManager.getLogger();

    @Bean
    public WebClient webClient(ReactiveClientRegistrationRepository clientRegistrations,
            ServerOAuth2AuthorizedClientRepository authorizedClients) {
        ServerOAuth2AuthorizedClientExchangeFilterFunction oauth = new ServerOAuth2AuthorizedClientExchangeFilterFunction(
                clientRegistrations, authorizedClients);
        oauth.setDefaultOAuth2AuthorizedClient(true);
        return WebClient.builder().filter(oauth).filter(this.logRequest()).build();
    }

    private ExchangeFilterFunction logRequest() {
        return ExchangeFilterFunction.ofRequestProcessor(clientRequest -> {
            log.info("Request: [{}] {}", clientRequest.method(), clientRequest.url());
            log.debug("Payload: {}", clientRequest.body());
            return Mono.just(clientRequest);
        });
    }
}

成功日志 :

   .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.3.1.RELEASE)

2020-06-26 20:36:08.380  INFO 15956 --- [           main] c.e.s.SampleOauth2Application            : Starting SampleOauth2Application on Anishs-MacBook-Pro.local with PID 15956 (/Users/anish/Downloads/sampleOauth2/target/classes started by anish in /Users/anish/Downloads/sampleOauth2)
2020-06-26 20:36:08.381  INFO 15956 --- [           main] c.e.s.SampleOauth2Application            : No active profile set, falling back to default profiles: default
2020-06-26 20:36:08.935  INFO 15956 --- [           main] ctiveUserDetailsServiceAutoConfiguration : 

Using generated security password: 7c63302f-f913-4aa1-852d-cb8445719acb

2020-06-26 20:36:09.132  INFO 15956 --- [           main] o.s.b.web.embedded.netty.NettyWebServer  : Netty started on port(s): 8080
2020-06-26 20:36:09.138  INFO 15956 --- [           main] c.e.s.SampleOauth2Application            : Started SampleOauth2Application in 0.978 seconds (JVM running for 1.313)

推荐