Open In App

How to Intercept a Request and Add Headers in WebFlux?

Last Updated : 28 May, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Spring WebFlux is the reactive stack web framework that allows developers to build non-blocking, asynchronous applications that can handle a large number of concurrent with fewer hardware resources. In this article, we will explore how to intercept the HTTP requests in the Spring WebFlux application and modify them by adding custom headers. This capability can be useful for a variety of cross-cutting concerns such as authentication, logging, and modifying the request or response headers.

Intercepting Requests in WebFlux

In Spring WebFlux, we can intercept the requests using a WebFliter. The WebFliter can operate on the non-blocking reactive WebFlux stack and allows us to manipulate the request and response to the objects before they can reach the controllers or after they can sent back to the client.

Key Terminologies:

  • Spring WebFlux: The reactive web framework is part of the Spring 5 framework and it can designed to build reactive applications. It supports non-blocking, event-driven programming and works on the Reactive Streams specification.
  • Reactive Programming: The programming paradigm is concerned with the data streams and the propagation of the change. It emphasizes asynchronous data handling and it is suited for applications that handle the large number of concurrent connections with minimal resource utilization.
  • WebFilter: In the context of Spring WebFlux, the WebFilter is the interface used for the intercepting web requests and responses. It provides the capability to modify the incoming server requests and outgoing responses.
  • Mono and Flux: These are the two core types in the Project Reactor. Mono can represent the single or empty asynchronous value. While Flux can represent the sequence of 0 to N asynchronous values.
  • ServerWebExchange: The central class in the Spring WebFlux can represent the context of the HTTP exchange the request and the response. It allows for the modifications to the request and response and provides access to additional server-related information.
  • Non-Blocking: Describes the mode of the operation that allows other processes to continue before the previous operation finishes, thus not blocking the execution thread.
  • Back Pressure: The mechanism in reactive systems that allows the consumers to signal the producer about how much data they can process and it can preventing the consumer from being overwhelmed by the data sent by the producer.
  • Event Loop: It handles the distribution of events across the different handlers and subscribers in a non-blocking fashion.
  • Asynchronous: It allows the unit of work to run separately from the main application thread and notifies the calling thread of its completion, failure or progress.

Implementation of Intercept a Request and Add Headers in WebFlux

We will develop a simple spring reactive project that can intercept requests and modify their headers by implementing the WebFilter. This filter allows us to inspect and transform the requests throughout the application.

Step 1: Create the Spring Boot WebFlux Project

Create a new Spring Boot project using Spring Initializr and add the required dependencies as mentioned below,

  • Spring Web Reactive
  • Lombok
  • Spring DevTools

After the project creation is done, the folder structure will be like below.

Project Folder Structure


Step 2: Configure the Application properties

Open the application.properties file and add the configuration for the server port in the project.

server.port=8080


Step 3: Implement the WebFilter

We will create a new class that implements the WebFilter. In this filter, we will manipulate the ServerHttpRequest to add the custom header of the application.

Go to src > main > java > org.example.springheaderwebflux > config > HeaderAdditionFilter and put the below code.

Java
package org.example.springheaderwebflux.config;

import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;

@Component
public class HeaderAdditionFilter implements WebFilter {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
        ServerWebExchange mutatedExchange = exchange.mutate()
                .request(exchange.getRequest().mutate().header("Custom-Header", "CustomValue").build())
                .build();
        return chain.filter(mutatedExchange);
    }
}


Step 4: Create the SampleController class

We will create a simple controller to demonstrate that the application is working.

Go to src > main > java > org.example.springheaderwebflux > controller > SampleController and put the below code.

Java
package org.example.springheaderwebflux.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Mono;

@RestController
public class SampleController {

    @GetMapping("/")
    public Mono<String> hello() {
        return Mono.just("Hello World!");
    }
}


Step 5: Main Class

No changes are required in the main class.

Java
package org.example.springheaderwebflux;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringHeaderWebfluxApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringHeaderWebfluxApplication.class, args);
    }

}


Step 6: Run the application

Now, we will run the application and it will start at port 8080.

Application Running


Endpoint Testing

Open the Postman tool and add the below request with the GET method and also add the custom header with header value then send the request.

GET http://localhost:8080/

Output:

Header Testing

This example project demonstrates how to Intercept a Request and Add Headers in WebFlux in the Spring Boot project.


Next Article

Similar Reads