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.
| 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 |
| 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) |
| 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 (default: 1) |
| SsoAutoAuthorize | Adds a fake SSO authorization for development purposes |
| TokenRelay | Forwards the OAuth2 access token to downstream resources |
AddRequestHeadersIfNotPresentAdds 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
AllowedRequestCookieCountDetermines if a matching request is allowed to proceed based on the number of cookies.
Configuration parameters:
amount: number of allowed cookies. AllowedRequestCookieCount=2
AllowedRequestHeadersCountDetermines if a matching request is allowed to proceed based on the number of headers.
Configuration parameters:
amount: number of allowed headers. AllowedRequestHeadersCount=4
AllowedRequestQueryParamsCountDetermines if a matching request is allowed to proceed based on the number query params.
Configuration parameters:
amount: number of allowed parameters. AllowedRequestQueryParamsCount=3
ApiKeyValidate 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
BasicAuthAdds a BasicAuth Authorization header to requests.
No parameters required.
BasicAuth
CircuitBreakerWraps routes in a circuit breaker.
Configuration parameters:
name: circuit breaker name.fallbackUri: reroute url, can be a local route or external handler.status codes: (optional) colon-separated list of status codes to match, in number or text format.failure rate: (optional) threshold above which the circuit breaker will be opened (default 50%).duration: (optional) time to wait before closing again (default 60s). CircuitBreaker=myCircuitBreaker,forward:/inCaseOfFailureUseThis,401:NOT_FOUND:500,10,30s
ClaimHeaderCopies data from a JWT claim into an HTTP header.
Configuration parameters:
Claim name: case sensitive name of the claim to pass.Header name: name of the HTTP header. ClaimHeader=sub,X-Claim-Sub
ClientCertificateHeaderValidate X-Forwarded-Client-Cert header certificate.
Configuration parameters:
domain pattern: X-Forwarded-Client-Cert value according to Kubernetes's ability to recognize client certificate's CA.certificate fingerprint: (optional) SSL certificate's fingerprint. ClientCertificateHeader=*.example.com,sha-1:aa:bb:00:99
CorsActivates CORS validations on a route.
Configuration parameters are organized as key-value pairs for CORS options:
allowedOriginsallowedMethodsallowedHeadersmaxAgeallowCredentialsallowedOriginPatterns Cors=[allowedOrigins:https://origin-1,allowedMethods:GET;POST;DELETE,allowedHeaders:*,maxAge:400,allowCredentials:true,allowedOriginPatterns:https://*.test.com:8080]
FallbackHeadersAdds any circuit breaker exception to a header. Requires the use of the CircuitBreaker filter in another route.
No parameters required.
FallbackHeaders
JwtKeyAdds multiple client JSON Web Token validation.
Activated on the Gateway resource, see the dedicated guide for full details on configuration.
filters:
jwtKey:
enabled: true
LocalResponseCacheOverrides 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
RateLimitDetermines if a matching request is allowed to proceed based on request volume.
Configuration parameters:
request limit: maximum number of requests accepted during the window.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.partition source: (optional) location of the partition key ('claim', 'header' or 'IPs').partition key: (optional) 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}
RemoveJsonAttributesResponseBodyRemoves JSON attributes and their values from JSON response bodies.
Configuration parameters:
attribute names: comma-separated list of the names of attributes to remove from a JSON response.delete recursively: (optional, boolean) configures the removal of attributes only at root level (false), or recursively (true) (default, false). RemoveJsonAttributesResponseBody=origin,foo,true
RewriteAllResponseHeadersRewrite multiple response headers at once.
Configuration parameters:
pattern to match: regular expression to match against header values.replacement: replacement value. RewriteAllResponseHeaders=\d,0
RewriteResponseBodyModifies 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:
pattern to match: regular expression to match against text in the response body.replacement: replacement value. RewriteResponseBody=foo:bar,/path-one/:/path-two/
RewriteJsonAttributesResponseBodyRewrite 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:
jsonpath: JSONPath expression to match against the response body.replacement: replacement value. RewriteJsonAttributesResponseBody=slides[1].title:Welcome,date:11-11-2022
RolesAuthorizes requests whose authorization contains one of the configured roles.
Configuration parameters:
roles: comma-separated list of authorized roles. Roles=role_01,role_02
ScopesAuthorizes 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
StoreIpAddressStore IP address value in the context of the application. For extension development only.
Configuration parameters:
attribute name: name used to store the IP as an exchange attribute. StoreIpAddress=ip
SSO loginRedirects 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
StoreHeaderStore a header value in the context of the application. For extension development only.
Configuration parameters:
headers: list of headers to check (the first one found is used).attribute name: name used to store the header value as an exchange attribute. StoreHeader=x-tracing-header,custom-id,x-custom-id,tracingParam
SsoAutoAuthorizeFor 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
TokenRelayForwards 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