Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE

1. Overview

Interceptors, also known as filters, are a feature in Spring that allows us to intercept client requests. This allows us to examine and transform the request before the controller handles it or returns response to the client.

In this tutorial, we’ll discuss various ways of intercepting a client request and adding custom headers using the WebFlux Framework. We’ll first explore how to do it for a specific endpoint. Then, we’ll determine the approach for intercepting all incoming requests.

2. Maven Dependency

We’ll be using the following spring-boot-starter-webflux Maven dependency for Spring Framework’s Reactive Web support:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-webflux</artifactId>
    <version>3.1.5</version>
</dependency>

3. Server Request Interception and Transformation

Spring WebFlux Filters can be categorized as WebFilters and HandlerFilterFunctions. We’ll use these filters to intercept server web requests and add new custom headers or modify existing ones.

3.1. Using WebFilter

WebFilter is a contract for processing server Web requests in a chained, interception-style manner. A WebFilter acts globally and, once enabled, intercepts all requests and responses.

First, we should define the annotation-based controller:

@GetMapping(value= "/trace-annotated")
public Mono<String> trace(@RequestHeader(name = "traceId") final String traceId) {
    return Mono.just("TraceId: ".concat(traceId));
}

Then, we intercept the server web request and add a new header, traceId, using the TraceWebFilter implementation:

@Component
public class TraceWebFilter implements WebFilter {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
        exchange.getRequest().mutate()
          .header("traceId", "ANNOTATED-TRACE-ID");
        return chain.filter(exchange);
    }
}

Now we could use WebTestClient to send a GET request to the trace-annotated endpoint and verify that the response contains the traceId header value we appended as “TraceId:  ANNOTATED-TRACE-ID“:

@Test
void whenCallAnnotatedTraceEndpoint_thenResponseContainsTraceId() {
    EntityExchangeResult<String> result = webTestClient.get()
      .uri("/trace-annotated")
      .exchange()
      .expectStatus()
      .isOk()
      .expectBody(String.class)
      .returnResult();

    String body = "TraceId: ANNOTATED-TRACE-ID";
    assertEquals(result.getResponseBody(), body);
}

The important point here is that we can’t directly modify the request headers like response headers since the request headers map is read-only:

@Override
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
    if (exchange.getRequest().getPath().toString().equals("/trace-exceptional")) {
        exchange.getRequest().getHeaders().add("traceId", "TRACE-ID");
    }
    return chain.filter(exchange);
 }

This implementation throws an UnsupportedOperationException.

Let’s use WebTestClient to verify that the filter throws an exception, causing a server error after sending a GET request to the trace-exceptional endpoint:

@GetMapping(value = "/trace-exceptional")
public Mono<String> traceExceptional() {
    return Mono.just("Traced");
}
@Test
void whenCallTraceExceptionalEndpoint_thenThrowsException() {
    EntityExchangeResult<Map> result = webTestClient.get()
      .uri("/trace-exceptional")
      .exchange()
      .expectStatus()
      .is5xxServerError()
      .expectBody(Map.class)
      .returnResult();

    assertNotNull(result.getResponseBody());
}

3.2. Using HandlerFilterFunction

In functional style, a router function intercepts a request and calls the appropriate handler function.

We can enable zero or more HandlerFilterFunctions, which act as functions that filter the HandlerFunction. The HandlerFilterFunction implementations only works for router-based ones.

As for the functional endpoint, we’ll have to create a handler first:

@Component
public class TraceRouterHandler {
    public Mono<ServerResponse> handle(final ServerRequest serverRequest) {
        String traceId = serverRequest.headers().firstHeader("traceId");
      
        assert traceId != null;
        Mono<String> body = Mono.just("TraceId: ".concat(traceId));
        return ok().body(body, String.class);
    }
}

After configuring the handler with the router configuration, we intercept the server web request and add a new header traceId using the TraceHandlerFilterFunction implementation:

public RouterFunction<ServerResponse> routes(TraceRouterHandler routerHandler) {
    return RouterFunctions
      .route(GET("/trace-functional-filter"), routerHandler::handle)
      .filter(new TraceHandlerFilterFunction());
}
public class TraceHandlerFilterFunction implements HandlerFilterFunction<ServerResponse, ServerResponse> {
    @Override
    public Mono<ServerResponse> filter(ServerRequest request, HandlerFunction<ServerResponse> handlerFunction) {
        ServerRequest serverRequest = ServerRequest.from(request)
          .header("traceId", "FUNCTIONAL-TRACE-ID")
          .build();
        return handlerFunction.handle(serverRequest);
    }
}

We can now verify that the response contains the traceId header value we appended as “TraceId:  FUNCTIONAL-TRACE-ID” after triggering a GET call to the trace-functional-filter endpoint:

@Test
void whenCallTraceFunctionalEndpoint_thenResponseContainsTraceId() {
    EntityExchangeResult<String> result = webTestClient.get()
      .uri("/trace-functional-filter")
      .exchange()
      .expectStatus()
      .isOk()
      .expectBody(String.class)
      .returnResult();

    String body = "TraceId: FUNCTIONAL-TRACE-ID";
    assertEquals(result.getResponseBody(), body);
}

3.3. Using Custom Processor Function

The processor function is similar to a router function, which intercepts a request and calls the appropriate handler function.

The functional routing API enables us to add zero or more custom Function instances that are applied before the HandlerFunction.

This filter function intercepts the server web request created by the builder and adds a new header, traceId:

public RouterFunction<ServerResponse> routes(TraceRouterHandler routerHandler) {
    return route()
      .GET("/trace-functional-before", routerHandler::handle)
      .before(request -> ServerRequest.from(request)
        .header("traceId", "FUNCTIONAL-TRACE-ID")
        .build())
      .build());
}

After sending a GET request to the trace-functional-before endpoint, let’s verify that the response contains the traceId header value we appended as “TraceId:  FUNCTIONAL-TRACE-ID“:

@Test
void whenCallTraceFunctionalBeforeEndpoint_thenResponseContainsTraceId() {
    EntityExchangeResult<String> result = webTestClient.get()
      .uri("/trace-functional-before")
      .exchange()
      .expectStatus()
      .isOk()
      .expectBody(String.class)
      .returnResult();

    String body = "TraceId: FUNCTIONAL-TRACE-ID";
    assertEquals(result.getResponseBody(), body);
}

4. Client Request Interception and Transformation

We’ll use ExchangeFilterFunctions to intercept client requests with Spring WebClient.

4.1. Using ExchangeFilterFunctions

ExchangeFilterFunction is a term associated with Spring WebClient. We use this to intercept client requests with the WebFlux WebClient. ExchangeFilterFunction is used to transform the request or the response before it’s sent or after it’s received.

Let’s define the exchange filter function to intercept web client requests and add a new header traceId. We’ll keep track of all request headers to verify the ExchangeFilterFunction:

public ExchangeFilterFunction modifyRequestHeaders(MultiValueMap<String, String> changedMap) {
    return (request, next) -> {
        ClientRequest clientRequest = ClientRequest.from(request)
          .header("traceId", "TRACE-ID")
          .build();
        changedMap.addAll(clientRequest.headers());
        return next.exchange(clientRequest);
    };
}

Since we defined the filter function, we can then attach it to the WebClient instance. This can only be done while we create the WebClient:

public WebClient webclient() {
    return WebClient.builder()
      .filter(modifyRequestHeaders(new LinkedMultiValueMap<>()))
      .build();
}

We can now use Wiremock to test the custom ExchangeFilterFunction:

@RegisterExtension
static WireMockExtension extension = WireMockExtension.newInstance()
  .options(wireMockConfig().dynamicPort().dynamicHttpsPort())
  .build();
@Test
void whenCallEndpoint_thenRequestHeadersModified() {
    extension.stubFor(get("/test").willReturn(aResponse().withStatus(200)
      .withBody("SUCCESS")));

    MultiValueMap<String, String> map = new LinkedMultiValueMap<>();

    WebClient webClient = WebClient.builder()
      .filter(modifyRequestHeaders(map))
      .build();
    String receivedResponse = triggerGetRequest(webClient);

    String body = "SUCCESS";
    Assertions.assertEquals(receivedResponse, body);
    Assertions.assertEquals("TRACE-ID", map.getFirst("traceId"));
}

Finally, with Wiremock, we have verified the ExchangeFilterFunction by checking that the new header traceId is available inside the MultivalueMap instance.

5. Conclusion

In this article, we explored different ways of intercepting and adding custom headers for both server web requests and web client requests.

First, we explored how to add custom headers for server web requests using WebFilter and HandlerFilterFunction. After that, we discussed how to do the same thing for WebClient requests using ExchangeFilterFunction.

As always, the complete source code for the tutorial is available over on GitHub.

Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE
res – REST with Spring (eBook) (everywhere)
Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.