Client Filters

You can register a client filter (ExchangeFilterFunction) through the WebClient.Builder in order to intercept and modify requests, as the following example shows:

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()

This can be used for cross-cutting concerns, such as authentication. The following example uses a filter for basic authentication 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()

Filters apply globally to every request. To change a filter’s behavior for a specific request, you can add request attributes to the ClientRequest that can then be accessed by all filters in the chain, as the following example shows:

Java
WebClient client = WebClient.builder()
		.filter((request, next) -> {
			Optional<Object> usr = request.attribute("myAttribute");
			// ...
		})
		.build();

client.get().uri("https://example.org/")
		.attribute("myAttribute", "...")
		.retrieve()
		.bodyToMono(Void.class);

	}
Kotlin
val client = WebClient.builder()
			.filter { request, _ ->
		val usr = request.attributes()["myAttribute"];
		// ...
	}.build()

	client.get().uri("https://example.org/")
			.attribute("myAttribute", "...")
			.retrieve()
			.awaitBody<Unit>()

You can also replicate an existing WebClient, insert new filters, or remove already registered filters. 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()