Spring 5 WebClient Basic Auth

Carvia Tech | July 26, 2020 | 2 min read | 0 views


In this article we will learn various methods for Basic Authentication in Spring 5 WebClient.

Spring Boot provides an auto-configured WebClient.Builder instance which we can use to create a customized version of WebClient.

We can always use WebClient.create(), but in that case, no auto-configuration or WebClientCustomizer will be applied.

Gradle setup

We must have Spring Webflux dependencies added to the project in order to use WebClient.

build.gradle
plugins {
    id 'java'
    id 'org.springframework.boot' version '2.3.2.RELEASE'
    id 'io.spring.dependency-management' version "1.0.9.RELEASE"
}

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-webflux'
}

Using ExchangeFilterFunctions

We can use ExchangeFilterFunctions.basicAuthentication filter while creating WebClient instance which will inject Basic Auth headers in each outgoing request.

Using ExchangeFilterFunctions
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.client.ExchangeFilterFunctions;
import org.springframework.web.reactive.function.client.WebClient;

@Component
public class WebClientTest {

    private final WebClient webClient;

    @Autowired
    public WebClientTest(WebClient.Builder builder) {   (1)
        webClient = builder
                .baseUrl("http://localhost:8080")
                .filter(ExchangeFilterFunctions.basicAuthentication("admin", "password"))
                .build();
    }
}
1 We are injecting Spring Boot auto-configured WebClient.Builder instance.

The only problem with this approach is that Basic Auth is configured at WebClient level, so all outgoing requests will have same basic auth headers.

Using Default Headers

Spring webclient has headers method that provides access to every header declared so far with the possibility to add, replace, or remove values.

Using default headers at WebClient Level
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.client.ExchangeFilterFunctions;
import org.springframework.web.reactive.function.client.WebClient;

@Component
public class WebClientTest {

    private final WebClient webClient;

    @Autowired
    public WebClientTest(WebClient.Builder builder) {
        webClient = builder
                .baseUrl("http://localhost:8080")
                .defaultHeaders(httpHeaders -> httpHeaders.setBasicAuth("admin", "password")) (1)
                .defaultHeaders(httpHeaders -> httpHeaders.setBearerAuth("<bearer token>")) (2)
                .build();
    }
}
1 Using default headers approach for Basic Auth
2 We can set bearer token instead of Basic Auth, depending upon your requirements

Request level headers

If you do not need Basic Auth setup at WebClient level, then you can overwrite headers at per request level, allowing you to use different headers for different urls.

Per request basic auth headers
public void test2() {
    final String flux = webClient.get()
            .uri("/secured/hello")
            .headers(httpHeaders -> httpHeaders.setBasicAuth("admin", "password"))
            .retrieve()
            .bodyToMono(String.class)
            .block();
    System.out.println(flux);
}

That' all.


Top articles in this category:
  1. Spring RestTemplate Basic Authentication
  2. Basic Auth Security in Spring Boot 2
  3. Disable SSL verification in Spring WebClient
  4. Spring Data ElasticSearch with Basic Auth
  5. Send Gupshup SMS using Java API
  6. Testing web layer in Spring Boot using WebMvcTest
  7. Spring Boot multi-part file upload


Find more on this topic:
Spring Framework image
Spring Framework

Spring Framework - MVC, Dependency Injection, Spring Hibernate, Spring Data JPA, Spring Boot and Spring Cloud for Microservices Architecture.

Last updated 1 week ago


Recommended books for interview preparation:

This website uses cookies to ensure you get the best experience on our website. more info