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
Step 1: Create a Spring Boot Application
<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
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();
}
}
Step 3: Create a Service to Consume the Secured 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
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)
);
}
}
Comments
Post a Comment
Leave Comment