springspring-webfluxgatewayspring-cloud-gateway

Spring cloud gateway request body to request header use by custom filter


I am new to webflux. I am having difficulty controlling data using webflux.

Body data is missing in the controller when writing as below. Is there a solution? Data sent as body value is set as header Reading the body data seems to be successful. However, data is not added to the header value, and the body value information is also lost.

@Component
@Slf4j
public class GetFormGatewayFilterFactory extends AbstractGatewayFilterFactory<GetFormGatewayFilterFactory.Config> {
    public GetFormGatewayFilterFactory() {
        super(Config.class);
    }
    @Override
    public GatewayFilter apply(Config config) {
        //Custom Pre Filter
        return (exchange, chain) -> {

            return DataBufferUtils.join(exchange.getRequest().getBody())
                    .flatMap(dataBuffer -> {
                        //바디값 읽어오기
                        byte[] bytes = new byte[dataBuffer.readableByteCount()];
                        dataBuffer.read(bytes);
                        DataBufferUtils.release(dataBuffer);
                        String body = new String(bytes, StandardCharsets.UTF_8);

                        //읽어온 바디값을 header값에 추가

                        return chain.filter(exchange.mutate().request(exchange.getRequest().mutate().header("headerName", body).build()).build());
                    });
        };
    }



    public static class Config {
//Put the configuration properties
    }

}```

Solution

  • One thing to keep in mind is that when reading the request body in Webflux, you will be consuming the Flux. It's important to note that this Flux can only be consumed once, which means you should cache it and pass the cache along to the controller. But caching the request body in Webflux is not the best idea since it negates some benefits of WebFlux. For additional information, please refer to the following link: https://stackoverflow.com/a/76250029/6933090

    Here you can find some additional information on how to cache the request body: https://www.baeldung.com/kotlin/spring-webflux-log-request-response-body