Spring Cloud Gateway Filters v4.0

Krzysztof Kocel

November 27, 2023


In one of the previous blog posts I described how Spring Cloud Gateway can be used to validate incoming Alexa requests.

Spring Cloud Gateway 4.0 introduced new interesting filters that can be used to simplify validation code even more.’.

Prior to their introduction, the most challenging part was reading the request body and making validations against it.

It turns out that one of the new filters solved exactly that pain-point.

Now instead of extending ModifyRequestBodyGatewayFilterFactory we can use CacheRequestBody filter:

spring:
  cloud:
    gateway:
      default-filters:
        - name: CacheRequestBody
          args:
            bodyClass: java.lang.String

Then in our filters we can access cached body from attribute:

import org.springframework.cloud.gateway.filter.GatewayFilterChain
import org.springframework.cloud.gateway.filter.GlobalFilter
import org.springframework.cloud.gateway.support.ServerWebExchangeUtils
import org.springframework.web.server.ServerWebExchange

class SampleBodyValidationFilter : GlobalFilter {

    override fun filter(exchange: ServerWebExchange, chain: GatewayFilterChain): Mono<Void> {
        // we have access to request body here
        val body: String? = exchange.getAttribute(ServerWebExchangeUtils.CACHED_REQUEST_BODY_ATTR)
        
        // ...
    }
}

This greatly simplified our codebase. Hope it will be helpful for you as well.

You can find sample code here