Spring Boot WebClient Basic Authentication

Carvia Tech | September 12, 2020 | 2 min read | 0 views


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

Authentication mechanisms

Spring Webclient provides different mechanisms for authentication:

ExchangeFilterFunctions

WebClient scoped filters that can be used for setting up authentication.

Default Headers

We can set default headers for each request at the WebClient level.

Request Level headers

This allows us to set authentication header at request level, so a single WebClient instance can use different credentials for different requests.

WebClientBuilder

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

You can head to https://start.spring.io/ for creating a Spring Boot starter project.

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

build.gradle
plugins {
    id 'java'
    id 'org.springframework.boot' version '2.3.3.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. Redis rate limiter in Spring Boot
  5. Spring Data ElasticSearch with Basic Auth
  6. SendGrid emails in Spring Boot
  7. Sendgrid Dynamic Templates with Spring Boot


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