Ваша конфигурация с пружинной загрузкой идеальна.
Root причина проблемы: Проблема в application.yaml. Либо конфигурация неверна, либо не выбрана из среды.
Итак, проблема не в версии OAuth2 , а в конфигурации в application.yaml.
Примечание: ReactiveClientRegistrationRepository
bean-компонент создается только при настройке клиента с указанием сведений о владельце приложения OAuth2.
Я создал новый проект из 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.
Затем я увидел, что не настраивал свойства в файле application.yml .
Я читал Spring Boot и OAuth2.0 Docs о том, как получить client-id и client-secret из github (пример), когда вы регистрируете в нем свое приложение с весенней загрузкой как приложение OAuth.
Как только я настроил приложение, оно начало работать .
Я использую spring -boot 2.3.1.RELEASE и OAuth2Client версии 5.3.3 .
My 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 клиента для application.yml :
spring:
security:
oauth2:
client:
registration:
github:
client-id: 22a7100de41c7308d346
client-secret: 05910ab890be29579e9c183443d92e756c450aaf
Ваш обновленный WebClientConfig @Configuration class:
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)