Filters are used in your SpringCloudGatewayRouteConfig to act on the incoming request or outgoing response to a matching route configuration.

Example uses for a filter could be in adding an HTTP header, or denying access based on an authorization token.

Spring Cloud Gateway OSS includes a number of GatewayFilter factories used to create filters for routes. For a complete list of these factories, see the Spring Cloud Gateway OSS documentation.

Spring Cloud Gateway for Kubernetes also provides a number of custom filters in addition to those included in the OSS project.

NoteSpring Cloud Gateway for Kubernetes sets StripPrefix=1 by default on every route, to deactivate it just set StripPrefix=0 in your configuration.

Available filters

Filter Description
AddRequestHeader Adds a header to a request
AddRequestHeadersIfNotPresent Adds headers if not present in the original request
AddRequestParameter Adds a request parameter to a request query string
AddResponseHeader Adds a header to a matching response
AllowedRequestCookieCount Determines if a matching request is allowed to proceed based on the number of cookies
AllowedRequestHeadersCount Determines if a matching request is allowed to proceed based on the number of headers
AllowedRequestQueryParamsCount Determines if a matching request is allowed to proceed based on the number of query parameters
ApiKey Validate API keys from X-API-Key header against those stored in Hashicorp Vault
BasicAuth Adds BasicAuth credentials as header to requests
CircuitBreaker Wraps routes in a circuit breaker
ClaimHeader Copies data from a JWT claim into an HTTP Header
ClientCertificateHeader Validate X-Fowarded-Client-Cert header certificate, and optionally its fingerprint
Cors DEPRECATED, see Configuring per-route Cross-Origin Resource Sharing (CORS) behavior via metadata below.
DeDupeResponseHeader Removes duplicates of certain headers
FallbackHeaders Adds circuit breaker exception to a header
JSONToGRPC Converts a JSON payload to a gRPC request
JwtKey Adds multiple client JWT token validation
JsonToXml Transforms Json body response into XML body response
LocalResponseCache Adds specific cache to the route. If the global cache is active, then the filter will override the default configuration
MapRequestHeader Maps a header from another one
PrefixPath Adds a prefix to a matching request path
PreserveHostHeader Preserves the original host header when sending a request
RateLimit Determines if a matching request is allowed to proceed based on request volume
RedirectTo Redirects a matching request to a given URL, returning a specified 3xx status code
RemoveJsonAttributesResponseBody Removes JSON attributes and their values from a JSON response body
RemoveRequestHeader Removes a header from a matching request
RemoveResponseHeader Removes a header from a response
RemoveRequestParameter Removes a query parameter from a matching request
RequestSize Rejects requests which are above a certain size (in bytes)
RestrictRequestHeaders Determines if a matching request is allowed to proceed based on the headers
Retry Retries a matching request
RewriteAllResponseHeaders Transforms response headers using regular expression match and replace
RewritePath Transforms the request path using regular expression match and replace
RewriteLocationResponseHeader Modifies the value of the location response header
RewriteResponseHeader Rewrite a response header value
RewriteResponseBody Modifies the response body of a request
RewriteJsonAttributesResponseBody Rewrite JSON attributes using JSONPath notation
Roles Authorizes requests whose authorization contains one of the configured roles
Scopes Authorizes requests whose authorization contains one of the configured scopes
SecureHeaders Adds best-practice security headers
SetPath Sets the request path
SetRequestHostHeader Overrides the host header value of matching requests
SetResponseHeader Sets a certain response header
SetStatus Sets the HTTP status of the response
SSO Login Redirects to authenticate if no valid Authorization token
StoreIpAddress Store IP address value in the context of the application
StoreHeader Store a header value in the context of the application
StripPrefix Strips a number of segments from the path of a matching request. By default it has value 1 on every configured route.
SsoAutoAuthorize Adds a fake SSO authorization for development purposes
TokenRelay Forwards the OAuth2 access token to downstream resources
XmlToJson Transforms XML body response into Json body response

AddRequestHeadersIfNotPresent

Adds headers if not present in the original request.

Configuration parameters:

  • headers: comma-separated list of key-value pairs (header name, header value)
    AddRequestHeadersIfNotPresent=Content-Type:application/json,Connection:keep-alive

AllowedRequestCookieCount

Determines if a matching request is allowed to proceed based on the number of cookies.

Configuration parameters:

  • cookieCount: number of allowed cookies.
    AllowedRequestCookieCount=2

AllowedRequestHeadersCount

Determines if a matching request is allowed to proceed based on the number of headers.

Configuration parameters:

  • headerCount: number of allowed headers.
    AllowedRequestHeadersCount=4

AllowedRequestQueryParamsCount

Determines if a matching request is allowed to proceed based on the number query params.

Configuration parameters:

  • paramsCount: number of allowed parameters.
    AllowedRequestQueryParamsCount=3

ApiKey

Validate API keys from the X-API-Key header against those stored in Hashicorp Vault.

Activated on the Gateway resource, see the dedicated guide for full details on configuration.

   filters:
      apiKey:
        enabled: true

BasicAuth

Adds a BasicAuth Authorization header to requests.

No parameters required.

    BasicAuth

CircuitBreaker

Wraps routes in a circuit breaker.

Configuration parameters:

  • name: circuit breaker name.
  • fallbackUri: reroute url, can be a local route or external handler.
  • statusCodes: (optional) colon-separated list of status codes to match, in number or text format.
  • failureRateThreshold: (optional) threshold above which the circuit breaker will be opened (default 50%).
  • waitIntervalInOpenState: (optional) time to wait before closing again (default 60s).
    CircuitBreaker=myCircuitBreaker,forward:/inCaseOfFailureUseThis,401:NOT_FOUND:500,10,30s

ClaimHeader

Copies data from a JWT claim into an HTTP header.

Configuration parameters:

  • claim: case sensitive name of the claim to pass.
  • headerName: name of the HTTP header.
    ClaimHeader=sub,X-Claim-Sub

ClientCertificateHeader

Validate X-Forwarded-Client-Cert header certificate.

Configuration parameters:

  • domain: X-Forwarded-Client-Cert value according to Kubernetes's ability to recognize client certificate's CA.
  • certificateFingerprint: (optional) SSL certificate's fingerprint.
    ClientCertificateHeader=*.example.com,sha-1:aa:bb:00:99

Cors

Activates CORS validations on a route.

Configuration parameters are organized as key-value pairs for CORS options:

  • allowedOrigins
  • allowedMethods
  • allowedHeaders
  • maxAge
  • allowCredentials
  • allowedOriginPatterns
    Cors=[allowedOrigins:https://origin-1,allowedMethods:GET;POST;DELETE,allowedHeaders:*,maxAge:400,allowCredentials:true,allowedOriginPatterns:https://*.test.com:8080]

FallbackHeaders

Adds any circuit breaker exception to a header. Requires the use of the CircuitBreaker filter in another route.

No parameters required.

    FallbackHeaders

JwtKey

Adds multiple client JSON Web Token validation.

Activated on the Gateway resource, see the dedicated guide for full details on configuration.

   filters:
      jwtKey:
        enabled: true

JsonToXml

Transforms JSON response body into XML response body

Configuration parameters:

  • wrapper: root tag name for the XML response, default root tag is response if an additional root tag is required to generate valid XML.

See the dedicated guide for full details and examples.

    JsonToXml=custom-response

LocalResponseCache

Overrides local response cache configuration for specific routes if global cache is activated.

Configuration parameters:

  • size: maximum allowed size of the cache entries for this route before cache eviction begins (in KB, MB and GB).
  • timeToLive: allowed lifespan of a cache entry before expiration (use the duration suffix s for seconds, m for minutes, or h for hours).
    LocalResponseCache=3m,1MB

RateLimit

Determines if a matching request is allowed to proceed based on request volume.

Configuration parameters:

  • limit: maximum number of requests accepted during the window.
  • duration: window duration in milliseconds. Alternatively the s, m or h suffixes can be used to specify the duration in seconds, minutes or hours.
  • keyLocation: (optional) location of the partition key ('claim', 'header' or 'IPs') and value used to partition request counters
    RateLimit=1,10s
    RateLimit=1,10s,{claim:client_id}
    RateLimit=1,10s,{header:client_id}
    RateLimit=2,10s,{IPs:2;127.0.0.1;192.168.0.1}

RemoveJsonAttributesResponseBody

Removes JSON attributes and their values from JSON response bodies.

Configuration parameters:

  • fieldList: comma-separated list of the names of attributes to remove from a JSON response.
  • deleteRecursively: (optional) boolean that configures the removal of attributes only at root level (false, default value), or recursively (true)
    RemoveJsonAttributesResponseBody=origin,foo,true

RestrictRequestHeaders

Determines if a matching request is allowed to proceed based on the headers. If there are any HTTP headers that are not in the headerList configuration (case insensitive) then a response of 403 Forbidden error will be returned to client.

Configuration parameters:

  • headerList: list of names of allowed headers (case insensitive).
    RestrictRequestHeaders=Content-Type,x-request-temp

Note: If any load balancers or network gateways add extra request headers, they need to be included in the list or the request will return an error.

RewriteAllResponseHeaders

Rewrite multiple response headers at once.

Configuration parameters:

  • regexp: regular expression to match against header values.
  • replacement: replacement value.
    RewriteAllResponseHeaders=\d,0

RewriteResponseBody

Modifies the body of a response.

Configuration parameters are organized as a comma-separated list of key-value pairs, where each pair takes the form pattern to match:replacement:

  • keyValues: list of regular expression to match against text in the response body and replacement value separated by commas.
    RewriteResponseBody=foo:bar,/path-one/:/path-two/

RewriteJsonAttributesResponseBody

Rewrite JSON attributes using JSONPath notation.

Configuration parameters are organized as a comma-separated list of key-value pairs, where each pair takes the form jsonpath:replacement:

  • keyValues: list of JSONPath expression to match against the response body and replacement value separated by commas.
    RewriteJsonAttributesResponseBody=slides[1].title:Welcome,date:11-11-2022

Roles

Authorizes requests whose authorization contains one of the configured roles.

Configuration parameters:

  • roles: comma-separated list of authorized roles.
    Roles=role_01,role_02

Scopes

Authorizes requests whose authorization contains one of the configured OAuth scopes.

Configuration parameters:

  • scopes: comma-separated list of authorized OAuth scopes.
    Scopes=api.read,api.write,user

StoreIpAddress

Store IP address value in the context of the application. For extension development only.

Configuration parameters:

  • parameterName: name used to store the IP as an exchange attribute.
    StoreIpAddress=ip

SSO login

Redirects to authenticate if no valid Authorization token is found.

Configured per route via a boolean flag in SpringCloudGatewayRouteConfig. See the dedicated guide for full details on configuration.

    routes:
      - ssoEnabled: true

StoreHeader

Store a header value in the context of the application. For extension development only.

Configuration parameters:

  • tracingHeaders: list of headers to check (the first one found is used); latest parameter of the list will be used to store the header value as an exchange attribute.
    StoreHeader=X-Tracing-Header,Custom-Id,X-Custom-Id,myTracingParam

SsoAutoAuthorize

For development only. Adds a fake SSO authorization for development purposes.

Configuration parameters:

  • headers: list of roles or scopes to set.
    SsoAutoAuthorize=SCOPE_test,ROLE_test

TokenRelay

Forwards OAuth2 access token to downstream resources.

Configured per route via a boolean flag in SpringCloudGatewayRouteConfig.

See the dedicated guide for full details on configuration.

    routes:
      - tokenRelay: true

XmlToJson

Transforms XML response body into JSON response body

No parameters required.

See the dedicated guide for full details and examples.

    XmlToJson
check-circle-line exclamation-circle-line close-line
Scroll to top icon