Spring Web Reactive | 2. WebClient | 2.5. Filters

You can register a client filter (ExchangeFilterFunction) through WebClient.Builder to intercept and modify requests, as shown below.

Java

WebClient client = WebClient.builder()
        .filter((request, next) -> {

            ClientRequest filtered = ClientRequest.from(request)
                    .header("foo", "bar")
                    .build();

            return next.exchange(filtered);
        })
        .build();

Kotlin

val client = WebClient.builder()
        .filter { request, next ->

            val filtered = ClientRequest.from(request)
                    .header("foo", "bar")
                    .build()

            next.exchange(filtered)
        }
        .build()

Filters can be used for cross-cutting concerns such as authentication. The following example uses a basic authentication filter through a static factory method.

Java

import static org.springframework.web.reactive.function.client.ExchangeFilterFunctions.basicAuthentication;

WebClient client = WebClient.builder()
        .filter(basicAuthentication("user", "password"))
        .build();

Kotlin

import org.springframework.web.reactive.function.client.ExchangeFilterFunctions.basicAuthentication

val client = WebClient.builder()
        .filter(basicAuthentication("user", "password"))
        .build()

You can create a new WebClient instance using another instance as the starting point. This lets you insert or remove filters without affecting the original WebClient. The following example inserts a basic authentication filter at index 0.

Java

import static org.springframework.web.reactive.function.client.ExchangeFilterFunctions.basicAuthentication;

WebClient client = webClient.mutate()
        .filters(filterList -> {
            filterList.add(0, basicAuthentication("user", "password"));
        })
        .build();

Kotlin

val client = webClient.mutate()
        .filters { it.add(0, basicAuthentication("user", "password")) }
        .build()