Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a WebClient-object in a spring application with oauth2

I'm developing a spring application (client) that is secured with an OAuth2 provider. This application should do some REST calls to another spring application (resource server). For performing the REST calls, I will use spring's WebClient.

I therefore try to create a bean of type WebClient as can be found in several blogs.

@Configuration
public class AppConfig {

    @Bean
    public WebClient webClient(ReactiveClientRegistrationRepository clientRegistrations) {
        ServerOAuth2AuthorizedClientExchangeFilterFunction oauth =
             new ServerOAuth2AuthorizedClientExchangeFilterFunction(clientRegistrations,
                new UnAuthenticatedServerOAuth2AuthorizedClientRepository());
        oauth.setDefaultClientRegistrationId("myprovider");
        return WebClient.builder().filter(oauth).build();
    }
}

When starting the application, I get the following error:

The following candidates were found but could not be injected:
    - Bean method 'clientRegistrationRepository' in 'ReactiveOAuth2ClientAutoConfiguration' not loaded because NoneNestedConditions 1 matched 0 did not; NestedCondition on ReactiveOAuth2ClientAutoConfiguration.NonServletApplicationCondition.ServletApplicationCondition found 'session' scope


Action:

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

As several websites recommend exactly this code for generating a WebClient instance when using OAuth2 authentication, I'm wondering what I'm doing wrong?

Do you have any suggestions for me?

Thanks.

like image 940
Raskar Kapak Avatar asked Jun 18 '19 15:06

Raskar Kapak


1 Answers

I got the same issue. I changed the code as provided in the video : https://www.youtube.com/watch?v=1N-xwmoN83w&t=1569s and that worked

@Bean
 public WebClient webClient(ClientRegistrationRepository clientRegistrationRepository , OAuth2AuthorizedClientRepository authorizedClientRepository) {
        ServletOAuth2AuthorizedClientExchangeFilterFunction oauth =
             new ServletOAuth2AuthorizedClientExchangeFilterFunction (clientRegistrationRepository , authorizedClientRepository);
        return WebClient.builder().apply(oauth.oauth2Configuration()).build();
    }

Hope that helps.

like image 140
Sradhanjali Phukan Avatar answered Sep 20 '22 22:09

Sradhanjali Phukan