OAuth2 with Spring WebClient

OAuth2 with Spring WebClient

Spring Security 5 provides OAuth2 support for Spring Webflux’s non-blocking WebClient class. Here we are going to discuss how to configure WebClient to access OAuth2 protected REST resources.

For example I’m going use “client credentials” grant type for the configuration. But the steps are same for the any grant type.

Step 01 : Dependencies

         <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-webflux</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-oauth2-client</artifactId>
        </dependency>

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

Step 02 : Configure the properties

Fist of all we have to set the OAuth2 credentials in the application.properties or application.yml file.

application.yml should be configured as follows

spring:
  application:
    name: outh2_WebClient

  security:
    oauth2:
      client:
        provider:
          authProvider:
            token-uri: https://authservice.com/apicall/token
        registration:
          authProvider:
            client-id: kzS85kk3pEqVAq4T41viw8dUf3ka
            client-secret: EbgaOBN56TQBvlD6Kw_9kCNmID0a
            authorization-grant-type: client_credentials

Note that “authProvider” can be any name you choose for your authentication provider.

Step 03 : Configure the bean

Next we should configure the WebClient to use the configurations we provided earlier. It would be as follows.

@Configuration
public class OAuthConfiguration {


    @Bean("authProvider") //bean qualifier
    WebClient mifeWebClient(ReactiveClientRegistrationRepository clientRegistrations) {
        ServerOAuth2AuthorizedClientExchangeFilterFunction oauth =
                new ServerOAuth2AuthorizedClientExchangeFilterFunction(
                        clientRegistrations,
                        new UnAuthenticatedServerOAuth2AuthorizedClientRepository());
        oauth.setDefaultClientRegistrationId("authProvider");
        return WebClient.builder()
                .filter(oauth)
                .build();
    }
}

Note that oauth.setDefaultClientRegistrationId(“authProvider”); should be the same name used in the property file under authentication provider.

Step 04 : Call an OAuth2 protected REST resource

First we Autowire the bean created earlier and use it to call the protected rest resource.

@Autowired
@Qualifier("authProvider")
private final WebClient webClient;
webClient.get()
        .uri("http://rest-url/api")
        .retrieve()
        .bodyToFlux(String.class)
        .subscribe(s -> System.out.println(s))

That’s it.

Thank you for taking the time to read this.

Leave a Comment

%d bloggers like this: