gateway built-in filter factory

Posted by shawnplr on Fri, 18 Feb 2022 22:00:57 +0100

Built in filter factory of Spring Cloud Gateway

Built in filter factory

Here, all filter factories built in Spring Cloud Gateway are simply sorted into a table. As follows:

Filter factoryeffectparameter
AddRequestHeaderAdd Header for original requestName and value of Header
AddRequestParameterAdd request parameters to the original requestParameter name and value
AddResponseHeaderAdd Header for original responseName and value of Header
DedupeResponseHeaderEliminate duplicate values in response headersHeader name and de duplication policy that need to be de duplicated
HystrixIntroduce circuit breaker protection of Hystrix for routingThe name of the HystrixCommand
FallbackHeadersAdd specific exception information to the request header of fallbackUriThe name of the Header
PrefixPathPrefix the original request pathprefix path
PreserveHostHeaderAdd a property of preserveHostHeader=true to the request, and the routing filter will check this property to decide whether to send the original Hostnothing
RequestRateLimiterIt is used to limit the current of requests. The current limiting algorithm is token bucketkeyResolver,rateLimiter,statusCode,denyEmptyKey,emptyKeyStatus
RedirectToRedirect the original request to the specified URLhttp status code and redirected url
RemoveHopByHopHeadersFilterDelete a series of headers specified by IETF organization for the original requestIt will be enabled by default. You can specify which headers to delete only through configuration
RemoveRequestHeaderDelete a Header for the original requestHeader name
RemoveResponseHeaderDelete a Header for the original responseHeader name
RewritePathRewrite the original request pathRegular expressions of original path and rewritten path
RewriteResponseHeaderOverride a Header in the original responseHeader name, regular expression of value, rewritten value
SaveSessionForce the WebSession::save operation before forwarding the requestnothing
secureHeadersAdd a series of security response headers to the original responseNone. It supports modifying the values of these security response headers
SetPathModify the original request pathModified path
SetResponseHeaderModify the value of a Header in the original responseHeader name, modified value
SetStatusModify the status code of the original responseHTTP status code, which can be a number or a string
StripPrefixThe path used to truncate the original requestUse a number to indicate the number of paths to truncate
RetryRetry for different responsesretries,statuses,methods,series
RequestSizeSets the size of the maximum request packet allowed to be received. If the requested packet size exceeds the set value, 413 Payload Too Large is returnedThe size of the request packet, in bytes. The default value is 5M
ModifyRequestBodyModify the content of the original request body before forwarding the requestModified request body content
ModifyResponseBodyModify the content of the original response bodyModified response body content
DefaultAdd filters for all routesFilter factory name and value

**Tips: * * each filter factory corresponds to an implementation class, and the names of these classes must end with GatewayFilterFactory, which is a convention of Spring Cloud Gateway. For example, the implementation class corresponding to AddRequestHeader is AddRequestHeaderGatewayFilterFactory.

1,AddRequestHeader GatewayFilter Factory

Add a Header for the original request. Configuration example:

spring:
  cloud:
    gateway:
      routes:
      - id: add_request_header_route
        uri: https://example.org
        filters:
        - AddRequestHeader=X-Request-Foo, Bar

Add a request header named X-Request-Foo and Bar to the original request

2,AddRequestParameter GatewayFilter Factory

Add request parameters and values to the original request. Configuration example:

spring:
  cloud:
    gateway:
      routes:
      - id: add_request_parameter_route
        uri: https://example.org
        filters:
        - AddRequestParameter=foo, bar

Add a parameter named Foo and the value bar to the original request, that is: foo=bar

3,AddResponseHeader GatewayFilter Factory

Add a Header for the original response. Configuration example:

spring:
  cloud:
    gateway:
      routes:
      - id: add_response_header_route
        uri: https://example.org
        filters:
        - AddResponseHeader=X-Response-Foo, Bar

Add a response header named X-Request-Foo with a value of Bar to the original response

4,DedupeResponseHeader GatewayFilter Factory

DedupeResponseHeader can eliminate duplicate values in the response Header according to the configured Header name and de duplication strategy. This is a new feature provided by Spring Cloud Greenwich SR2. It cannot be used earlier than this version.

If we set CORS (cross domain solution) headers on both gateway and microservice, if we do not make any configuration, the value of CORS Header obtained from request - > Gateway - > microservice will be as follows:

Access-Control-Allow-Credentials: true, true
Access-Control-Allow-Origin: https://musk.mars, https://musk.mars

You can see that the values of the two headers are repeated. If you want to duplicate the values of the two headers, you need to use the DedupeResponseHeader. Configuration example:

spring:
  cloud:
    gateway:
      routes:
      - id: dedupe_response_header_route
        uri: https://example.org
        filters:
        # If there are multiple headers that need to be de duplicated, separate them with spaces
        - DedupeResponseHeader=Access-Control-Allow-Credentials Access-Control-Allow-Origin

De duplication strategy:

  • RETAIN_FIRST: default value, keep the first value
  • RETAIN_LAST: keep the last value
  • RETAIN_UNIQUE: keep all unique values in the order they first appear

If you want to have a comprehensive understanding of the filter factory, it is recommended to read the source code of the filter factory, because there are detailed comments and examples in the source code, which is better than the official documents: org springframework. cloud. gateway. filter. factory. DedupeResponseHeaderGatewayFilterFactory

5,Hystrix GatewayFilter Factory

Introduce circuit breaker protection of Hystrix for routing. Configuration example:

spring:
  cloud:
    gateway:
      routes:
      - id: hystrix_route
        uri: https://example.org
        filters:
        - Hystrix=myCommandName

Hystrix is the first generation fault-tolerant component of Spring Cloud, but it has entered the maintenance mode. In the future, hystrix will be removed by Spring Cloud and replaced by Alibaba Sentinel/Resilience4J. Therefore, this article will not introduce it in detail. If you are interested, you can refer to the official documents:

6,FallbackHeaders GatewayFilter Factory

This parameter is also used to forward the uri supported by the factory to the previous one when an exception occurs. The FallbackHeaders filter factory can add a Header when forwarding the request to the uri, and the value of this Header is the specific exception information. Configuration example:

spring:
  cloud:
    gateway:
      routes:
      - id: ingredients
        uri: lb://ingredients
        predicates:
        - Path=//ingredients/**
        filters:
        - name: Hystrix
          args:
            name: fetchIngredients
            fallbackUri: forward:/fallback
      - id: ingredients-fallback
        uri: http://localhost:9994
        predicates:
        - Path=/fallback
        filters:
        - name: FallbackHeaders
          args:
            executionExceptionTypeHeaderName: Test-Header

There is no detailed introduction here. If you are interested, please refer to the official documents:

7,PrefixPath GatewayFilter Factory

Add a prefix path to the original request path. Configuration example:

spring:
  cloud:
    gateway:
      routes:
      - id: prefixpath_route
        uri: https://example.org
        filters:
        - PrefixPath=/mypath

This configuration causes access to ${GATEWAY_URL}/hello to be forwarded to https://example.org/mypath/hello

8,PreserveHostHeader GatewayFilter Factory

Add a property of preserveHostHeader=true to the request, and the routing filter will check this property to determine whether to send the original Host Header. Configuration example:

spring:
  cloud:
    gateway:
      routes:
      - id: preserve_host_route
        uri: https://example.org
        filters:
        - PreserveHostHeader

If not set, the Header named Host will be controlled by Http Client

9,RequestRateLimiter GatewayFilter Factory

It is used to limit the current of requests. The current limiting algorithm is token bucket. Configuration example:

spring:
  cloud:
    gateway:
      routes:
      - id: requestratelimiter_route
        uri: https://example.org
        filters:
        - name: RequestRateLimiter
          args:
            redis-rate-limiter.replenishRate: 10
            redis-rate-limiter.burstCapacity: 20

Since another article has described how to use the filter factory to realize gateway current limiting, it will not be repeated here:

Or refer to official documents:

10,RedirectTo GatewayFilter Factory

Redirect the original request to the specified Url. Configuration example:

spring:
  cloud:
    gateway:
      routes:
      - id: redirect_route
        uri: https://example.org
        filters:
        - RedirectTo=302, https://acme.org

This configuration causes access to ${GATEWAY_URL}/hello to be redirected to https://acme.org/hello And carry a Location:http://acme.org And the HTTP status code of the returned client is 302

matters needing attention:

  • The HTTP status code should be 3xx, for example, 301
  • The URL must be a legal URL, which will be used as the value of Location Header

11,RemoveHopByHopHeadersFilter GatewayFilter Factory

Delete for original request IETF A series of headers specified by the organization. The headers deleted by default are as follows:

  • Connection
  • Keep-Alive
  • Proxy-Authenticate
  • Proxy-Authorization
  • TE
  • Trailer
  • Transfer-Encoding
  • Upgrade

You can specify which headers to delete only through configuration. Configuration example:

spring:
  cloud:
    gateway:
      filter:
        remove-hop-by-hop:
          # Multiple headers are separated by commas (,)
          headers: Connection,Keep-Alive

12,RemoveRequestHeader GatewayFilter Factory

Delete a Header for the original request. Configuration example:

spring:
  cloud:
    gateway:
      routes:
      - id: removerequestheader_route
        uri: https://example.org
        filters:
        - RemoveRequestHeader=X-Request-Foo

Delete the request header named X-Request-Foo in the original request

13,RemoveResponseHeader GatewayFilter Factory

Delete a Header for the original response. Configuration example:

spring:
  cloud:
    gateway:
      routes:
      - id: removeresponseheader_route
        uri: https://example.org
        filters:
        - RemoveResponseHeader=X-Response-Foo

Delete the response header named X-Request-Foo in the original response

14,RewritePath GatewayFilter Factory

Rewrite the original request path through regular expression. Configuration example:

spring:
  cloud:
    gateway:
      routes:
      - id: rewritepath_route
        uri: https://example.org
        predicates:
        - Path=/foo/**
        filters:
        # Parameter 1 is the regular expression of the original path, and parameter 2 is the regular expression of the rewritten path
        - RewritePath=/foo/(?<segment>.*), /$\{segment}

This configuration enables the path to be rewritten as / bar and then forwarded when accessing / foo/bar, that is, it will be forwarded to https://example.org/bar . It should be noted that due to YAML syntax, it needs to be replaced with $$

15,RewriteResponseHeader GatewayFilter Factory

Rewrite a Header in the original response. Configuration example:

spring:
  cloud:
    gateway:
      routes:
      - id: rewriteresponseheader_route
        uri: https://example.org
        filters:
        # Parameter 1 is the Header name, parameter 2 is the regular expression of the value, and parameter 3 is the rewritten value
        - RewriteResponseHeader=X-Response-Foo, password=[^&]+, password=***

The significance of this configuration is: if the value of X-Response-Foo in the response header is / 42? user=ford&password=omg!what & Flag = true, then it will be rewritten as / 42 according to the configured value? User = Ford & password = * * * & Flag = true, that is, the password=omg!what is rewritten as password=***

16,SaveSession GatewayFilter Factory

Before forwarding the request, force the WebSession::save operation. Configuration example:

spring:
  cloud:
    gateway:
      routes:
      - id: save_session
        uri: https://example.org
        predicates:
        - Path=/foo/**
        filters:
        - SaveSession

It is mainly used for delaying data storage (data is not immediately persistent) like Spring Session, and it is hoped to ensure that the session state is saved before request forwarding. If you integrate spring security with Spring Session and want to ensure that all security information is transmitted to downstream machines, you need to configure this filter.

17,secureHeaders GatewayFilter Factory

secureHeaders filter factory is mainly for reference This blog A series of security response Headers are added to the original response. The following Headers (including values) will be added by default:

  • X-Xss-Protection:1; mode=block
  • Strict-Transport-Security:max-age=631138519
  • X-Frame-Options:DENY
  • X-Content-Type-Options:nosniff
  • Referrer-Policy:no-referrer
  • Content-Security-Policy:default-src 'self' https:; font-src 'self' https: data:; img-src 'self' https: data:; object-src 'none'; script-src https:; style-src 'self' https: 'unsafe-inline'
  • X-Download-Options:noopen
  • X-Permitted-Cross-Domain-Policies:none

If you want to modify the values of these Headers, you need to use the suffixes corresponding to these Headers, as follows:

  • xss-protection-header
  • strict-transport-security
  • frame-options
  • content-type-options
  • referrer-policy
  • content-security-policy
  • download-options
  • permitted-cross-domain-policies

Configuration example:

spring:
  cloud:
    gateway:
      filter:
        secure-headers:
          # Modify the value of X-Xss-Protection to 2; mode=unblock
          xss-protection-header: 2; mode=unblock

If you want to disable some headers, you can use the following configuration:

spring:
  cloud:
    gateway:
      filter:
        secure-headers:
          # Multiple are separated by commas (,)
          disable: frame-options,download-options

18,SetPath GatewayFilter Factory

Modify the original request path. Configuration example:

spring:
  cloud:
    gateway:
      routes:
      - id: setpath_route
        uri: https://example.org
        predicates:
        - Path=/foo/{segment}
        filters:
        - SetPath=/{segment}

This configuration causes access to ${GATEWAY_URL}/foo/bar to be forwarded to https://example.org/bar That is, the original / foo/bar is changed to / bar

19,SetResponseHeader GatewayFilter Factory

Modify the value of a Header in the original response. Configuration example:

spring:
  cloud:
    gateway:
      routes:
      - id: setresponseheader_route
        uri: https://example.org
        filters:
        - SetResponseHeader=X-Response-Foo, Bar

Change the value of X-Response-Foo in the original response to Bar

20,SetStatus GatewayFilter Factory

Modify the status code of the original response. Configuration example:

spring:
  cloud:
    gateway:
      routes:
      - id: setstatusstring_route
        uri: https://example.org
        filters:
        # String form
        - SetStatus=BAD_REQUEST
      - id: setstatusint_route
        uri: https://example.org
        filters:
        # Digital form
        - SetStatus=401

The value of setstatus D can be a number or a string. But it must be the value in the Spring HttpStatus enumeration class. The above two configurations can return the HTTP status code 401.

21,StripPrefix GatewayFilter Factory

Used to truncate the path of the original request. Configuration example:

spring:
  cloud:
    gateway:
      routes:
      - id: nameRoot
        uri: http://nameservice
        predicates:
        - Path=/name/**
        filters:
        # The number indicates the number of paths to truncate
        - StripPrefix=2

As configured above, if the requested path is / name/bar/foo, it will be truncated to / Foo and forwarded, that is, two paths will be truncated.

22,Retry GatewayFilter Factory

Retry can be configured for different HTTP response codes, for example:

spring:
  cloud:
    gateway:
      routes:
      - id: retry_test
        uri: http://localhost:8080/flakey
        predicates:
        - Host=*.retry.com
        filters:
        - name: Retry
          args:
            retries: 3
            statuses: BAD_GATEWAY

The following parameters can be configured:

  • Retries: number of retries
  • statuses: the status code that needs to be retried. The value is org springframework. http. In httpstatus
  • methods: the request method that needs to be retried. The value is at org springframework. http. In httpmethod
  • Series: HTTP status code sequence. The value is at org springframework. http. HttpStatus. In series

23,RequestSize GatewayFilter Factory

Set the size of the maximum request packet that can be received. Configuration example:

spring:
  cloud:
    gateway:
      routes:
      - id: request_size_route
      uri: http://localhost:8080/upload
      predicates:
      - Path=/upload
      filters:
      - name: RequestSize
        args:
          # In bytes
          maxSize: 5000000

If the request packet size exceeds the set value, 413 Payload Too Large and an errorMessage will be returned

24,Modify Request Body GatewayFilter Factory

Before forwarding the request, modify the content of the original request body. The filter factory can only be configured through code and does not support configuration in the configuration file. Code example:

@Bean
public RouteLocator routes(RouteLocatorBuilder builder) {
    return builder.routes()
        .route("rewrite_request_obj", r -> r.host("*.rewriterequestobj.org")
            .filters(f -> f.prefixPath("/httpbin")
                .modifyRequestBody(String.class, Hello.class, MediaType.APPLICATION_JSON_VALUE,
                    (exchange, s) -> return Mono.just(new Hello(s.toUpperCase())))).uri(uri))
        .build();
}
 
static class Hello {
    String message;
 
    public Hello() { }
 
    public Hello(String message) {
        this.message = message;
    }
 
    public String getMessage() {
        return message;
    }
 
    public void setMessage(String message) {
        this.message = message;
    }
}

Tips: the filter factory is in BETA status, and the API may change in the future. Please use it with caution in the production environment

25,Modify Response Body GatewayFilter Factory

It can be used to modify the content of the original response body. The filter factory can only be configured through code, and it does not support configuration in the configuration file. Code example:

@Bean
public RouteLocator routes(RouteLocatorBuilder builder) {
    return builder.routes()
        .route("rewrite_response_upper", r -> r.host("*.rewriteresponseupper.org")
            .filters(f -> f.prefixPath("/httpbin")
                .modifyResponseBody(String.class, String.class,
                    (exchange, s) -> Mono.just(s.toUpperCase()))).uri(uri)
        .build();
}

Tips: the filter factory is in BETA status, and the API may change in the future. Please use it with caution in the production environment

26,Default Filters

Default Filters is used to add filter factories for all routes, that is, the filter factories configured through Default Filter will act on all routes. Configuration example:

spring:
  cloud:
    gateway:
      default-filters:
      - AddResponseHeader=X-Response-Default-Foo, Default-Bar
      - PrefixPath=/httpbin

The content of the article is provided by a friend who learns from each other
Official documents:

Topics: Java Spring Spring Boot