Spring Boot WebClient Basic Authentication

To consume the secured REST API with the WebClient, you need to set up your WebClient with basic authentication headers. In this tutorial, we will see how to create a Spring Boot application that sets up WebClient to consume the /greeting endpoint of a REST API secured with Basic Authentication.

Spring's WebClient is a modern, non-blocking, and reactive client for HTTP requests. It was introduced in Spring 5 as part of the reactive stack web framework and is intended to replace the RestTemplate with a more modern, flexible, and powerful tool.

Prerequisites

In this tutorial, we are going to use WebClient to consume the secured REST APIs hence first we need to expose the REST API and secure it using basic authentication. Refer to the below tutorial to create and expose REST API and secure it using Spring Security's basic authentication: Spring Security Basic Authentication

REST API endpoint URL: http://localhost:8080/greeting

Step 1: Create a Spring Boot Application 

You can start by creating a Spring Boot application and adding the necessary dependencies in your 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-security</artifactId>
    </dependency>

Step 2: Configure WebClient with Basic Authentication 

Next, you'll need to configure WebClient to include the Basic Authentication header.
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.http.HttpHeaders;
import org.springframework.util.Base64Utils;

@Configuration
public class WebClientConfig {

    @Bean
    public WebClient webClient() {
        return WebClient.builder()
            .defaultHeader(HttpHeaders.AUTHORIZATION, "Basic " + Base64Utils.encodeToString("admin:admin".getBytes()))
            .build();
    }
}
Replace "admin:admin" with your actual username and password for the secured REST API. This header will be added to every request made by the WebClient.

Step 3: Create a Service to Consume the Secured Endpoint 

Now, you can create a service to consume the /greeting endpoint.
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;

@Service
public class WebClientService {

    private final WebClient webClient;

    @Autowired
    public GreetingService(WebClient webClient) {
        this.webClient = webClient;
    }

    public Mono<String> getGreeting() {
        return webClient.get()
                .uri("http://localhost:8080/greeting")
                .retrieve()
                .bodyToMono(String.class);
    }
}

Step 4: Use WebClient Service in the Application

Next, to test WebClient with basic authentication, let's quickly create the CommandLineRunner bean in your main application class:
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;

@SpringBootApplication
public class WebClientBasicAuthApplication {

    public static void main(String[] args) {
        SpringApplication.run(WebClientBasicAuthApplication.class, args);
    }

    // CommandLineRunner bean that calls the GreetingService to fetch and print the greeting
    @Bean
    public CommandLineRunner run(GreetingService greetingService) {
        return args -> greetingService.getGreeting().subscribe(
                greeting -> System.out.println("Greeting: " + greeting),
                error -> System.err.println("There was an error: " + error)
        );
    }
}
In the run method of the CommandLineRunner, we subscribe to the Mono<String> returned by the GreetingService.getGreeting() method. Upon success, it prints the greeting to the console. On error, it prints the error message.

Conclusion 

By following these steps, you've successfully created a Spring Boot application that uses WebClient to consume a secured REST API using Basic Authentication. The combination of reactive programming and security makes your application both efficient and secure. Remember to handle errors and exceptions that may occur due to incorrect credentials or unavailable services to make your client more robust.

Comments