diff --git a/multi/multi__gatewayfilter_factories.html b/multi/multi__gatewayfilter_factories.html new file mode 100644 index 00000000..7a9af8ba --- /dev/null +++ b/multi/multi__gatewayfilter_factories.html @@ -0,0 +1,184 @@ + + + 5. GatewayFilter Factories

5. GatewayFilter Factories

Route filters allow the modification of the incoming HTTP request or outgoing HTTP response in some manner. Route filters are scoped to a particular route. Spring Cloud Gateway includes many built-in GatewayFilter Factories.

5.1 AddRequestHeader GatewayFilter Factory

The AddRequestHeader GatewayFilter Factory takes a name and value parameter.

application.yml.  +

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

+

This will add X-Request-Foo:Bar header to the downstream request’s headers for all matching requests.

5.2 AddRequestParameter GatewayFilter Factory

The AddRequestParameter GatewayFilter Factory takes a name and value parameter.

application.yml.  +

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

+

This will add foo=bar to the downstream request’s query string for all matching requests.

5.3 AddResponseHeader GatewayFilter Factory

The AddResponseHeader GatewayFilter Factory takes a name and value parameter.

application.yml.  +

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

+

This will add X-Response-Foo:Bar header to the downstream response’s headers for all matching requests.

5.4 Hystrix GatewayFilter Factory

The Hystrix GatewayFilter Factory requires a single name parameter, which is the name of the HystrixCommand.

application.yml.  +

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

+

This wraps the remaining filters in a HystrixCommand with command name myCommandName.

The Hystrix filter can also accept an optional fallbackUri parameter. Currently, only forward: schemed URIs are supported. If the fallback is called, the request will be forwarded to the controller matched by the URI.

application.yml.  +

spring:
+  cloud:
+    gateway:
+      routes:
+      - id: hystrix_route
+        uri: lb://backing-service:8088
+        predicates:
+        - Path=/consumingserviceendpoint
+        filters:
+        - name: Hystrix
+          args:
+            name: fallbackcmd
+            fallbackUri: forward:/incaseoffailureusethis
+        - RewritePath=/consumingserviceendpoint, /backingserviceendpoint

+

This will forward to the /incaseoffailureusethis URI when the Hystrix fallback is called. Note that this example also demonstrates (optional) Spring Cloud Netflix Ribbon load-balancing via the lb prefix on the destination URI.

5.5 PrefixPath GatewayFilter Factory

The PrefixPath GatewayFilter Factory takes a single prefix parameter.

application.yml.  +

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

+

This will prefix /mypath to the path of all matching requests. So a request to /hello, would be sent to /mypath/hello.

5.6 PreserveHostHeader GatewayFilter Factory

The PreserveHostHeader GatewayFilter Factory has not parameters. This filter, sets a request attribute that the routing filter will inspect to determine if the original host header should be sent, rather than the host header determined by the http client.

application.yml.  +

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

+

This will prefix /mypath to the path of all matching requests. So a request to /hello, would be sent to /mypath/hello.

5.7 RequestRateLimiter GatewayFilter Factory

The RequestRateLimiter GatewayFilter Factory takes three parameters: replenishRate, burstCapacity & keyResolverName.

replenishRate is how many requests per second do you want a user to be allowed to do.

burstCapacity TODO: document burst capacity

keyResolver is a bean that implements the KeyResolver interface. In configuration, reference the bean by name using SpEL. #{@myKeyResolver} is a SpEL expression referencing a bean with the name myKeyResolver.

KeyResolver.java.  +

public interface KeyResolver {
+	Mono<String> resolve(ServerWebExchange exchange);
+}

+

The KeyResolver interface allows pluggable strategies to derive the key for limiting requests. In future milestones, there will be some KeyResolver implementations.

The redis implementation is based off of work done at Stripe. It requires the use of the spring-boot-starter-data-redis-reactive Spring Boot starter.

application.yml.  +

spring:
+  cloud:
+    gateway:
+      routes:
+      - id: requestratelimiter_route
+        uri: http://example.org
+        filters:
+        - RequestRateLimiter=10, 20, #{@userKeyResolver}

+

Config.java.  +

@Bean
+KeyResolver userKeyResolver() {
+    return exchange -> Mono.just(exchange.getRequest().getQueryParams().getFirst("user"));
+}

+

This defines a request rate limit of 10 per user. The KeyResolver is a simple one that gets the user request parameter (note: this is not recommended for production).

5.8 RedirectTo GatewayFilter Factory

The RedirectTo GatewayFilter Factory takes a status and a url parameter. The status should be a 300 series redirect http code, such as 301. The url should be a valid url. This will be the value of the Location header.

application.yml.  +

spring:
+  cloud:
+    gateway:
+      routes:
+      - id: prefixpath_route
+        uri: http://example.org
+        filters:
+        - RedirectTo=302, http://acme.org

+

This will send a status 302 with a Location:http://acme.org header to perform a redirect.

5.9 RemoveNonProxyHeaders GatewayFilter Factory

The RemoveNonProxyHeaders GatewayFilter Factory removes headers from forwarded requests. The default list of headers that is removed comes from the IETF.

The default removed headers are:

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

To change this, set the spring.cloud.gateway.filter.remove-non-proxy-headers.headers property to the list of header names to remove.

5.10 RemoveRequestHeader GatewayFilter Factory

The RemoveRequestHeader GatewayFilter Factory takes a name parameter. It is the name of the header to be removed.

application.yml.  +

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

+

This will remove the X-Request-Foo header before it is sent downstream.

5.11 RemoveResponseHeader GatewayFilter Factory

The RemoveResponseHeader GatewayFilter Factory takes a name parameter. It is the name of the header to be removed.

application.yml.  +

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

+

This will remove the X-Response-Foo header from the response before it is returned to the gateway client.

5.12 RewritePath GatewayFilter Factory

The RewritePath GatewayFilter Factory takes a path regexp parameter and a replacement parameter. This uses Java regular expressions for a flexible way to rewrite the request path.

application.yml.  +

spring:
+  cloud:
+    gateway:
+      routes:
+      - id: rewritepath_route
+        uri: http://example.org
+        predicates:
+        - Path=/foo/**
+        filters:
+        - RewritePath=/foo/(?<segment>.*), /$\{segment}

+

For a request path of /foo/bar, this will set the path to /bar before making the downstream request. Notice the $\ which is replaced with $ because of the YAML spec.

5.13 SaveSession GatewayFilter Factory

The SaveSession GatewayFilter Factory forces a WebSession::save operation before forwarding the call downstream. This is of particular use when +using something like Spring Session with a lazy data store and need to ensure the session state has been saved before making the forwarded call.

application.yml.  +

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

+

If you are integrating Spring Security with Spring Session, and want to ensure security details have been forwarded to the remote process, this is critical.

5.14 SecureHeaders GatewayFilter Factory

The SecureHeaders GatewayFilter Factory adds a number of headers to the response at the reccomendation from this blog post.

The following headers are added (allong with default values):

  • 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

To change the default values set the appropriate property in the spring.cloud.gateway.filter.secure-headers namespace:

Property to change:

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

5.15 SetPath GatewayFilter Factory

The SetPath GatewayFilter Factory takes a path template parameter. It offers a simple way to manipulate the request path by allowing templated segments of the path. This uses the uri templates from Spring Framework. Multiple matching segments are allowed.

application.yml.  +

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

+

For a request path of /foo/bar, this will set the path to /bar before making the downstream request.

5.16 SetResponseHeader GatewayFilter Factory

The SetResponseHeader GatewayFilter Factory takes name and value parameters.

application.yml.  +

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

+

This GatewayFilter replaces all headers with the given name, rather than adding. So if the downstream server responded with a X-Response-Foo:1234, this would be replaced with X-Response-Foo:Bar, which is what the gateway client would receive.

5.17 SetStatus GatewayFilter Factory

The SetStatus GatewayFilter Factory takes a single status parameter. It must be a valid Spring HttpStatus. It may be the integer value 404 or the string representation of the enumeration NOT_FOUND.

application.yml.  +

spring:
+  cloud:
+    gateway:
+      routes:
+      - id: setstatusstring_route
+        uri: http://example.org
+        filters:
+        - SetStatus=BAD_REQUEST
+      - id: setstatusint_route
+        uri: http://example.org
+        filters:
+        - SetStatus=401

+

In either case, the HTTP status of the response will be set to 401.

5.18 StripPrefix GatewayFilter Factory

The StripPrefix GatewayFilter Factory takes one paramter, parts. The parts parameter indicated the number of parts in the path to strip from the request before sending it downstream.

application.yml.  +

spring:
+  cloud:
+    gateway:
+      routes:
+      - id: nameRoot
+        uri: http://nameservice
+        predicates:
+        - Path=/name/**
+        filters:
+        - StripPrefix=2

+

When a request is made through the gateway to /name/bar/foo the request made to nameservice will look like http://nameservice/foo.

\ No newline at end of file diff --git a/multi/multi__global_filters.html b/multi/multi__global_filters.html index 7080f01c..b7a50987 100644 --- a/multi/multi__global_filters.html +++ b/multi/multi__global_filters.html @@ -1,3 +1,3 @@ - 6. Global Filters

6. Global Filters

The GlobalFilter interface has the same signature as GatewayFilter. These are special filters that are conditionally applied to all routes. (This interface and usage are subject to change in future milestones).

6.1 Combined Global Filter and GatewayFilter Ordering

TODO: document ordering

6.2 Forward Routing Filter

The ForwardRoutingFilter looks for a URI in the exchange attribute ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR. If the url has a forward scheme (ie forward:///localendpoint), it will use the Spring DispatcherHandler to handler the request. The unmodified original url is appended to the list in the ServerWebExchangeUtils.GATEWAY_ORIGINAL_REQUEST_URL_ATTR attribute.

6.3 LoadBalancerClient Filter

The LoadBalancerClientFilter looks for a URI in the exchange attribute ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR. If the url has a lb scheme (ie lb://myservice), it will use the Spring Cloud LoadBalancerClient to resolve the name (myservice in the previous example) to an actual host and port and replace the URI in the same attribute. The unmodified original url is appended to the list in the ServerWebExchangeUtils.GATEWAY_ORIGINAL_REQUEST_URL_ATTR attribute. The filter will also look in the ServerWebExchangeUtils.GATEWAY_SCHEME_PREFIX_ATTR attribute to see if it equals lb and then the same rules apply.

6.4 Netty Routing Filter

The Netty Routing Filter runs if the url located in the ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR exchange attribute has a http or https scheme. It uses the Netty HttpClient to make the downstream proxy request. The response is put in the ServerWebExchangeUtils.CLIENT_RESPONSE_ATTR exchange attribute for use in a later filter. (There is an experimental WebClientHttpRoutingFilter that performs the same function, but does not require netty)

6.5 Netty Write Response Filter

The NettyWriteResponseFilter runs if there is a Netty HttpClientResponse in the ServerWebExchangeUtils.CLIENT_RESPONSE_ATTR exchange attribute. It is run after all other filters have completed and writes the proxy response back to the gateway client response. (There is an experimental WebClientWriteResponseFilter that performs the same function, but does not require netty)

6.6 RouteToRequestUrl Filter

The RouteToRequestUrlFilter runs if there is a Route object in the ServerWebExchangeUtils.GATEWAY_ROUTE_ATTR exchange attribute. It creates a new URI, based off of the request URI, but updated with the URI attribute of the Route object. The new URI is placed in the ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR exchange attribute`.

If the URI has a scheme prefix, such as lb:ws://serviceid, the lb scheme is stripped from the URI and placed in the ServerWebExchangeUtils.GATEWAY_SCHEME_PREFIX_ATTR for use later in the filter chain.

6.7 Websocket Routing Filter

The Websocket Routing Filter runs if the url located in the ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR exchange attribute has a ws or wss scheme. It uses the Spring Web Socket infrastructure to forward the Websocket request downstream.

Websockets may be load-balanced by prefixing the URI with lb, such as lb:ws://serviceid.

\ No newline at end of file + 6. Global Filters

6. Global Filters

The GlobalFilter interface has the same signature as GatewayFilter. These are special filters that are conditionally applied to all routes. (This interface and usage are subject to change in future milestones).

6.1 Combined Global Filter and GatewayFilter Ordering

TODO: document ordering

6.2 Forward Routing Filter

The ForwardRoutingFilter looks for a URI in the exchange attribute ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR. If the url has a forward scheme (ie forward:///localendpoint), it will use the Spring DispatcherHandler to handler the request. The unmodified original url is appended to the list in the ServerWebExchangeUtils.GATEWAY_ORIGINAL_REQUEST_URL_ATTR attribute.

6.3 LoadBalancerClient Filter

The LoadBalancerClientFilter looks for a URI in the exchange attribute ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR. If the url has a lb scheme (ie lb://myservice), it will use the Spring Cloud LoadBalancerClient to resolve the name (myservice in the previous example) to an actual host and port and replace the URI in the same attribute. The unmodified original url is appended to the list in the ServerWebExchangeUtils.GATEWAY_ORIGINAL_REQUEST_URL_ATTR attribute. The filter will also look in the ServerWebExchangeUtils.GATEWAY_SCHEME_PREFIX_ATTR attribute to see if it equals lb and then the same rules apply.

6.4 Netty Routing Filter

The Netty Routing Filter runs if the url located in the ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR exchange attribute has a http or https scheme. It uses the Netty HttpClient to make the downstream proxy request. The response is put in the ServerWebExchangeUtils.CLIENT_RESPONSE_ATTR exchange attribute for use in a later filter. (There is an experimental WebClientHttpRoutingFilter that performs the same function, but does not require netty)

6.5 Netty Write Response Filter

The NettyWriteResponseFilter runs if there is a Netty HttpClientResponse in the ServerWebExchangeUtils.CLIENT_RESPONSE_ATTR exchange attribute. It is run after all other filters have completed and writes the proxy response back to the gateway client response. (There is an experimental WebClientWriteResponseFilter that performs the same function, but does not require netty)

6.6 RouteToRequestUrl Filter

The RouteToRequestUrlFilter runs if there is a Route object in the ServerWebExchangeUtils.GATEWAY_ROUTE_ATTR exchange attribute. It creates a new URI, based off of the request URI, but updated with the URI attribute of the Route object. The new URI is placed in the ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR exchange attribute`.

If the URI has a scheme prefix, such as lb:ws://serviceid, the lb scheme is stripped from the URI and placed in the ServerWebExchangeUtils.GATEWAY_SCHEME_PREFIX_ATTR for use later in the filter chain.

6.7 Websocket Routing Filter

The Websocket Routing Filter runs if the url located in the ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR exchange attribute has a ws or wss scheme. It uses the Spring Web Socket infrastructure to forward the Websocket request downstream.

Websockets may be load-balanced by prefixing the URI with lb, such as lb:ws://serviceid.

\ No newline at end of file diff --git a/multi/multi_gateway-request-predicates-factories.html b/multi/multi_gateway-request-predicates-factories.html index 6a6f8394..091de917 100644 --- a/multi/multi_gateway-request-predicates-factories.html +++ b/multi/multi_gateway-request-predicates-factories.html @@ -1,6 +1,6 @@ - 4. Route Predicate Factories

4. Route Predicate Factories

Spring Cloud Gateway matches routes as part of the Spring WebFlux HandlerMapping infrastructure. Spring Cloud Gateway includes many built-in Route Predicate Factories. All of these predicates match on different attributes of the HTTP request. Multiple Route Predicate Factories can be combined and are combined via logical and.

4.1 After Route Predicate Factory

The After Route Predicate Factory takes one parameter, a datetime. This predicate matches requests that happen after the current datetime.

application.yml.  + 4. Route Predicate Factories

4. Route Predicate Factories

Spring Cloud Gateway matches routes as part of the Spring WebFlux HandlerMapping infrastructure. Spring Cloud Gateway includes many built-in Route Predicate Factories. All of these predicates match on different attributes of the HTTP request. Multiple Route Predicate Factories can be combined and are combined via logical and.

4.1 After Route Predicate Factory

The After Route Predicate Factory takes one parameter, a datetime. This predicate matches requests that happen after the current datetime.

application.yml. 

spring:
   cloud:
     gateway:
@@ -72,7 +72,7 @@
         uri: http://example.org
         predicates:
         - Path=/foo/{segment}

-

This route would match if the request path was, for example: /foo/1 or /foo/bar.

This predicate extracts the URI template variables (like segment defined in the example above) as a map of names and values and places it in the ServerWebExchange.getAttributes() with a key defined in PathRoutePredicate.URL_PREDICATE_VARS_ATTR. Those values are then available for use by GatewayFilter Factories

4.9 Query Route Predicate Factory

The Query Route Predicate Factory takes two parameters: a required param and an optional regexp.

application.yml.  +

This route would match if the request path was, for example: /foo/1 or /foo/bar.

This predicate extracts the URI template variables (like segment defined in the example above) as a map of names and values and places it in the ServerWebExchange.getAttributes() with a key defined in PathRoutePredicate.URL_PREDICATE_VARS_ATTR. Those values are then available for use by GatewayFilter Factories

4.9 Query Route Predicate Factory

The Query Route Predicate Factory takes two parameters: a required param and an optional regexp.

application.yml. 

spring:
   cloud:
     gateway:
@@ -90,7 +90,7 @@
         uri: http://example.org
         predicates:
         - Query=foo, ba.

-

This route would match if the request contained a foo query parameter whose value matched the ba. regexp, so bar and baz would match.

4.10 RemoteAddr Route Predicate Factory

The RemoteAddr Route Predicate Factory takes a list (min size 1) of CIDR-notation (IPv4 or IPv6) strings, e.g. 192.168.0.1/16 (where 192.168.0.1 is an IP address and 16 is a subnet mask.

application.yml.  +

This route would match if the request contained a foo query parameter whose value matched the ba. regexp, so bar and baz would match.

4.10 RemoteAddr Route Predicate Factory

The RemoteAddr Route Predicate Factory takes a list (min size 1) of CIDR-notation (IPv4 or IPv6) strings, e.g. 192.168.0.1/16 (where 192.168.0.1 is an IP address and 16 is a subnet mask).

application.yml. 

spring:
   cloud:
     gateway:
@@ -99,4 +99,20 @@
         uri: http://example.org
         predicates:
         - RemoteAddr=192.168.1.1/24

-

This route would match if the remote address of the request was, for example, 192.168.1.10.

\ No newline at end of file +

This route would match if the remote address of the request was, for example, 192.168.1.10.

4.10.1 Modifying the way remote addresses are resolved

By default the RemoteAddr Route Predicate Factory uses the remote address from the incoming request. +This may not match the actual client IP address if Spring Cloud Gateway sits behind a proxy layer.

You can customize the way that the remote address is resolved by setting a custom RemoteAddressResolver. +Spring Cloud Gateway comes with one non-default remote address resolver which is based off of the X-Forwarded-For header, XForwardedRemoteAddressResolver.

XForwardedRemoteAddressResolver has two static constructor methods which take different approaches to security:

XForwardedRemoteAddressResolver::trustAllXForwardedRemoteAddressResolver returns a RemoteAddressResolver which always takes the first IP address found in the X-Forwarded-For header. +This approach is vulnerable to spoofing, as a malicious client could set an initial value for the X-Forwarded-For which would be accepted by the resolver.

XForwardedRemoteAddressResolver::maxTrustedIndexXForwardedRemoteAddressResolver takes an index which correlates to the number of trusted infrastructure running in front of Spring Cloud Gateway. +If Spring Cloud Gateway is, for example only accessible via HAProxy, then a value of 1 should be used. +If two hops of trusted infrastructure are required before Spring Cloud Gateway is accessible, then a value of 2 should be used.

Given the following header value:

X-Forwarded-For: 0.0.0.1, 0.0.0.2, 0.0.0.3

The maxTrustedIndex values below will yield the following remote addresses.

maxTrustedIndexresult

[Integer.MIN_VALUE,0]

(invalid, IllegalArgumentException during initialization)

1

0.0.0.3

2

0.0.0.2

3

0.0.0.1

[4, Integer.MAX_VALUE]

0.0.0.1

Using Java config:

GatewayConfig.java

RemoteAddressResolver resolver = XForwardedRemoteAddressResolver
+    .maxTrustedIndexXForwardedRemoteAddressResolver(1);
+
+...
+
+.route("direct-route",
+    r -> r.remoteAddr("10.1.1.1", "10.10.1.1/24")
+        .uri("https://downstream1")
+.route("proxied-route",
+    r -> r.remoteAddr(resolver,  "10.10.1.1", "10.10.1.1/24")
+        .uri("https://downstream2")
+)
\ No newline at end of file diff --git a/multi/multi_spring-cloud-gateway.html b/multi/multi_spring-cloud-gateway.html index 180e1072..eef4de04 100644 --- a/multi/multi_spring-cloud-gateway.html +++ b/multi/multi_spring-cloud-gateway.html @@ -1,3 +1,3 @@ - Spring Cloud Gateway

Spring Cloud Gateway


Table of Contents

1. How to Include Spring Cloud Gateway
2. Glossary
3. How It Works
4. Route Predicate Factories
4.1. After Route Predicate Factory
4.2. Before Route Predicate Factory
4.3. Between Route Predicate Factory
4.4. Cookie Route Predicate Factory
4.5. Header Route Predicate Factory
4.6. Host Route Predicate Factory
4.7. Method Route Predicate Factory
4.8. Path Route Predicate Factory
4.9. Query Route Predicate Factory
4.10. RemoteAddr Route Predicate Factory
5. GatewayFilter Factories
5.1. AddRequestHeader GatewayFilter Factory
5.2. AddRequestParameter GatewayFilter Factory
5.3. AddResponseHeader GatewayFilter Factory
5.4. Hystrix GatewayFilter Factory
5.5. PrefixPath GatewayFilter Factory
5.6. PreserveHostHeader GatewayFilter Factory
5.7. RequestRateLimiter GatewayFilter Factory
5.8. RedirectTo GatewayFilter Factory
5.9. RemoveNonProxyHeaders GatewayFilter Factory
5.10. RemoveRequestHeader GatewayFilter Factory
5.11. RemoveResponseHeader GatewayFilter Factory
5.12. RewritePath GatewayFilter Factory
5.13. SaveSession GatewayFilter Factory
5.14. SecureHeaders GatewayFilter Factory
5.15. SetPath GatewayFilter Factory
5.16. SetResponseHeader GatewayFilter Factory
5.17. SetStatus GatewayFilter Factory
5.18. StripPrefix GatewayFilter Factory
6. Global Filters
6.1. Combined Global Filter and GatewayFilter Ordering
6.2. Forward Routing Filter
6.3. LoadBalancerClient Filter
6.4. Netty Routing Filter
6.5. Netty Write Response Filter
6.6. RouteToRequestUrl Filter
6.7. Websocket Routing Filter
7. Configuration
7.1. Fluent Java Routes API
7.2. DiscoveryClient Route Definition Locator
8. Actuator API
9. Developer Guide
9.1. Writing Custom Route Predicate Factories
9.2. Writing Custom GatewayFilter Factories
9.3. Writing Custom Global Filters
9.4. Writing Custom Route Locators and Writers
10. Building a Simple Gateway Using Spring MVC
\ No newline at end of file + Spring Cloud Gateway

Spring Cloud Gateway


Table of Contents

1. How to Include Spring Cloud Gateway
2. Glossary
3. How It Works
4. Route Predicate Factories
4.1. After Route Predicate Factory
4.2. Before Route Predicate Factory
4.3. Between Route Predicate Factory
4.4. Cookie Route Predicate Factory
4.5. Header Route Predicate Factory
4.6. Host Route Predicate Factory
4.7. Method Route Predicate Factory
4.8. Path Route Predicate Factory
4.9. Query Route Predicate Factory
4.10. RemoteAddr Route Predicate Factory
4.10.1. Modifying the way remote addresses are resolved
5. GatewayFilter Factories
5.1. AddRequestHeader GatewayFilter Factory
5.2. AddRequestParameter GatewayFilter Factory
5.3. AddResponseHeader GatewayFilter Factory
5.4. Hystrix GatewayFilter Factory
5.5. PrefixPath GatewayFilter Factory
5.6. PreserveHostHeader GatewayFilter Factory
5.7. RequestRateLimiter GatewayFilter Factory
5.8. RedirectTo GatewayFilter Factory
5.9. RemoveNonProxyHeaders GatewayFilter Factory
5.10. RemoveRequestHeader GatewayFilter Factory
5.11. RemoveResponseHeader GatewayFilter Factory
5.12. RewritePath GatewayFilter Factory
5.13. SaveSession GatewayFilter Factory
5.14. SecureHeaders GatewayFilter Factory
5.15. SetPath GatewayFilter Factory
5.16. SetResponseHeader GatewayFilter Factory
5.17. SetStatus GatewayFilter Factory
5.18. StripPrefix GatewayFilter Factory
6. Global Filters
6.1. Combined Global Filter and GatewayFilter Ordering
6.2. Forward Routing Filter
6.3. LoadBalancerClient Filter
6.4. Netty Routing Filter
6.5. Netty Write Response Filter
6.6. RouteToRequestUrl Filter
6.7. Websocket Routing Filter
7. Configuration
7.1. Fluent Java Routes API
7.2. DiscoveryClient Route Definition Locator
8. Actuator API
9. Developer Guide
9.1. Writing Custom Route Predicate Factories
9.2. Writing Custom GatewayFilter Factories
9.3. Writing Custom Global Filters
9.4. Writing Custom Route Locators and Writers
10. Building a Simple Gateway Using Spring MVC
\ No newline at end of file diff --git a/single/spring-cloud-gateway.html b/single/spring-cloud-gateway.html index d1fcb24b..cae59765 100644 --- a/single/spring-cloud-gateway.html +++ b/single/spring-cloud-gateway.html @@ -1,6 +1,6 @@ - Spring Cloud Gateway

Spring Cloud Gateway


Table of Contents

1. How to Include Spring Cloud Gateway
2. Glossary
3. How It Works
4. Route Predicate Factories
4.1. After Route Predicate Factory
4.2. Before Route Predicate Factory
4.3. Between Route Predicate Factory
4.4. Cookie Route Predicate Factory
4.5. Header Route Predicate Factory
4.6. Host Route Predicate Factory
4.7. Method Route Predicate Factory
4.8. Path Route Predicate Factory
4.9. Query Route Predicate Factory
4.10. RemoteAddr Route Predicate Factory
5. GatewayFilter Factories
5.1. AddRequestHeader GatewayFilter Factory
5.2. AddRequestParameter GatewayFilter Factory
5.3. AddResponseHeader GatewayFilter Factory
5.4. Hystrix GatewayFilter Factory
5.5. PrefixPath GatewayFilter Factory
5.6. PreserveHostHeader GatewayFilter Factory
5.7. RequestRateLimiter GatewayFilter Factory
5.8. RedirectTo GatewayFilter Factory
5.9. RemoveNonProxyHeaders GatewayFilter Factory
5.10. RemoveRequestHeader GatewayFilter Factory
5.11. RemoveResponseHeader GatewayFilter Factory
5.12. RewritePath GatewayFilter Factory
5.13. SaveSession GatewayFilter Factory
5.14. SecureHeaders GatewayFilter Factory
5.15. SetPath GatewayFilter Factory
5.16. SetResponseHeader GatewayFilter Factory
5.17. SetStatus GatewayFilter Factory
5.18. StripPrefix GatewayFilter Factory
6. Global Filters
6.1. Combined Global Filter and GatewayFilter Ordering
6.2. Forward Routing Filter
6.3. LoadBalancerClient Filter
6.4. Netty Routing Filter
6.5. Netty Write Response Filter
6.6. RouteToRequestUrl Filter
6.7. Websocket Routing Filter
7. Configuration
7.1. Fluent Java Routes API
7.2. DiscoveryClient Route Definition Locator
8. Actuator API
9. Developer Guide
9.1. Writing Custom Route Predicate Factories
9.2. Writing Custom GatewayFilter Factories
9.3. Writing Custom Global Filters
9.4. Writing Custom Route Locators and Writers
10. Building a Simple Gateway Using Spring MVC

2.0.0.BUILD-SNAPSHOT

This project provides an API Gateway built on top of the Spring Ecosystem, including: Spring 5, Spring Boot 2 and Project Reactor. Spring Cloud Gateway aims to provide a simple, yet effective way to route to APIs and provide cross cutting concerns to them such as: security, monitoring/metrics, and resiliency.

1. How to Include Spring Cloud Gateway

To include Spring Cloud Gateway in your project use the starter with group org.springframework.cloud + Spring Cloud Gateway

Spring Cloud Gateway


Table of Contents

1. How to Include Spring Cloud Gateway
2. Glossary
3. How It Works
4. Route Predicate Factories
4.1. After Route Predicate Factory
4.2. Before Route Predicate Factory
4.3. Between Route Predicate Factory
4.4. Cookie Route Predicate Factory
4.5. Header Route Predicate Factory
4.6. Host Route Predicate Factory
4.7. Method Route Predicate Factory
4.8. Path Route Predicate Factory
4.9. Query Route Predicate Factory
4.10. RemoteAddr Route Predicate Factory
4.10.1. Modifying the way remote addresses are resolved
5. GatewayFilter Factories
5.1. AddRequestHeader GatewayFilter Factory
5.2. AddRequestParameter GatewayFilter Factory
5.3. AddResponseHeader GatewayFilter Factory
5.4. Hystrix GatewayFilter Factory
5.5. PrefixPath GatewayFilter Factory
5.6. PreserveHostHeader GatewayFilter Factory
5.7. RequestRateLimiter GatewayFilter Factory
5.8. RedirectTo GatewayFilter Factory
5.9. RemoveNonProxyHeaders GatewayFilter Factory
5.10. RemoveRequestHeader GatewayFilter Factory
5.11. RemoveResponseHeader GatewayFilter Factory
5.12. RewritePath GatewayFilter Factory
5.13. SaveSession GatewayFilter Factory
5.14. SecureHeaders GatewayFilter Factory
5.15. SetPath GatewayFilter Factory
5.16. SetResponseHeader GatewayFilter Factory
5.17. SetStatus GatewayFilter Factory
5.18. StripPrefix GatewayFilter Factory
6. Global Filters
6.1. Combined Global Filter and GatewayFilter Ordering
6.2. Forward Routing Filter
6.3. LoadBalancerClient Filter
6.4. Netty Routing Filter
6.5. Netty Write Response Filter
6.6. RouteToRequestUrl Filter
6.7. Websocket Routing Filter
7. Configuration
7.1. Fluent Java Routes API
7.2. DiscoveryClient Route Definition Locator
8. Actuator API
9. Developer Guide
9.1. Writing Custom Route Predicate Factories
9.2. Writing Custom GatewayFilter Factories
9.3. Writing Custom Global Filters
9.4. Writing Custom Route Locators and Writers
10. Building a Simple Gateway Using Spring MVC

2.0.0.BUILD-SNAPSHOT

This project provides an API Gateway built on top of the Spring Ecosystem, including: Spring 5, Spring Boot 2 and Project Reactor. Spring Cloud Gateway aims to provide a simple, yet effective way to route to APIs and provide cross cutting concerns to them such as: security, monitoring/metrics, and resiliency.

1. How to Include Spring Cloud Gateway

To include Spring Cloud Gateway in your project use the starter with group org.springframework.cloud and artifact id spring-cloud-starter-gateway. See the Spring Cloud Project page for details on setting up your build system with the current Spring Cloud Release Train.

If you include the starter, but, for some reason, you do not want the gateway to be enabled, set spring.cloud.gateway.enabled=false.

[Important]Important

Spring Cloud Gateway requires the Netty runtime provided by Spring Boot and Spring Webflux. It does not work in a traditional Servlet Container or built as a WAR.

2. Glossary

  • Route: Route the basic building block of the gateway. It is defined by an ID, a destination URI, a collection of predicates and a collection of filters. A route is matched if aggregate predicate is true.
  • Predicate: This is a Java 8 Function Predicate. The input type is a Spring Framework ServerWebExchange. This allows developers to match on anything from the HTTP request, such as headers or parameters.
  • Filter: These are instances Spring Framework GatewayFilter constructed in with a specific factory. Here, requests and responses can be modified before or after sending the downstream request.

3. How It Works

Spring Cloud Gateway Diagram

Clients make requests to Spring Cloud Gateway. If the Gateway Handler Mapping determines that a request matches a Route, it is sent to the Gateway Web Handler. This handler runs sends the request through a filter chain that is specific to the request. The reason the filters are divided by the dotted line, is that filters may execute logic before the proxy request is sent or after. All "pre" filter logic is executed, then the proxy request is made. After the proxy request is made, the "post" filter logic is executed.

[Note]Note

URIs defined in routes without a port will get a default port set to 80 and 443 for HTTP and HTTPS URIs respectively.

4. Route Predicate Factories

Spring Cloud Gateway matches routes as part of the Spring WebFlux HandlerMapping infrastructure. Spring Cloud Gateway includes many built-in Route Predicate Factories. All of these predicates match on different attributes of the HTTP request. Multiple Route Predicate Factories can be combined and are combined via logical and.

4.1 After Route Predicate Factory

The After Route Predicate Factory takes one parameter, a datetime. This predicate matches requests that happen after the current datetime.

application.yml. 

spring:
@@ -74,7 +74,7 @@ for details on setting up your build system with the current Spring Cloud Releas
         uri: http://example.org
         predicates:
         - Path=/foo/{segment}

-

This route would match if the request path was, for example: /foo/1 or /foo/bar.

This predicate extracts the URI template variables (like segment defined in the example above) as a map of names and values and places it in the ServerWebExchange.getAttributes() with a key defined in PathRoutePredicate.URL_PREDICATE_VARS_ATTR. Those values are then available for use by GatewayFilter Factories

4.9 Query Route Predicate Factory

The Query Route Predicate Factory takes two parameters: a required param and an optional regexp.

application.yml.  +

This route would match if the request path was, for example: /foo/1 or /foo/bar.

This predicate extracts the URI template variables (like segment defined in the example above) as a map of names and values and places it in the ServerWebExchange.getAttributes() with a key defined in PathRoutePredicate.URL_PREDICATE_VARS_ATTR. Those values are then available for use by GatewayFilter Factories

4.9 Query Route Predicate Factory

The Query Route Predicate Factory takes two parameters: a required param and an optional regexp.

application.yml. 

spring:
   cloud:
     gateway:
@@ -92,7 +92,7 @@ for details on setting up your build system with the current Spring Cloud Releas
         uri: http://example.org
         predicates:
         - Query=foo, ba.

-

This route would match if the request contained a foo query parameter whose value matched the ba. regexp, so bar and baz would match.

4.10 RemoteAddr Route Predicate Factory

The RemoteAddr Route Predicate Factory takes a list (min size 1) of CIDR-notation (IPv4 or IPv6) strings, e.g. 192.168.0.1/16 (where 192.168.0.1 is an IP address and 16 is a subnet mask.

application.yml.  +

This route would match if the request contained a foo query parameter whose value matched the ba. regexp, so bar and baz would match.

4.10 RemoteAddr Route Predicate Factory

The RemoteAddr Route Predicate Factory takes a list (min size 1) of CIDR-notation (IPv4 or IPv6) strings, e.g. 192.168.0.1/16 (where 192.168.0.1 is an IP address and 16 is a subnet mask).

application.yml. 

spring:
   cloud:
     gateway:
@@ -101,7 +101,23 @@ for details on setting up your build system with the current Spring Cloud Releas
         uri: http://example.org
         predicates:
         - RemoteAddr=192.168.1.1/24

-

This route would match if the remote address of the request was, for example, 192.168.1.10.

5. GatewayFilter Factories

Route filters allow the modification of the incoming HTTP request or outgoing HTTP response in some manner. Route filters are scoped to a particular route. Spring Cloud Gateway includes many built-in GatewayFilter Factories.

5.1 AddRequestHeader GatewayFilter Factory

The AddRequestHeader GatewayFilter Factory takes a name and value parameter.

application.yml.  +

This route would match if the remote address of the request was, for example, 192.168.1.10.

4.10.1 Modifying the way remote addresses are resolved

By default the RemoteAddr Route Predicate Factory uses the remote address from the incoming request. +This may not match the actual client IP address if Spring Cloud Gateway sits behind a proxy layer.

You can customize the way that the remote address is resolved by setting a custom RemoteAddressResolver. +Spring Cloud Gateway comes with one non-default remote address resolver which is based off of the X-Forwarded-For header, XForwardedRemoteAddressResolver.

XForwardedRemoteAddressResolver has two static constructor methods which take different approaches to security:

XForwardedRemoteAddressResolver::trustAllXForwardedRemoteAddressResolver returns a RemoteAddressResolver which always takes the first IP address found in the X-Forwarded-For header. +This approach is vulnerable to spoofing, as a malicious client could set an initial value for the X-Forwarded-For which would be accepted by the resolver.

XForwardedRemoteAddressResolver::maxTrustedIndexXForwardedRemoteAddressResolver takes an index which correlates to the number of trusted infrastructure running in front of Spring Cloud Gateway. +If Spring Cloud Gateway is, for example only accessible via HAProxy, then a value of 1 should be used. +If two hops of trusted infrastructure are required before Spring Cloud Gateway is accessible, then a value of 2 should be used.

Given the following header value:

X-Forwarded-For: 0.0.0.1, 0.0.0.2, 0.0.0.3

The maxTrustedIndex values below will yield the following remote addresses.

maxTrustedIndexresult

[Integer.MIN_VALUE,0]

(invalid, IllegalArgumentException during initialization)

1

0.0.0.3

2

0.0.0.2

3

0.0.0.1

[4, Integer.MAX_VALUE]

0.0.0.1

Using Java config:

GatewayConfig.java

RemoteAddressResolver resolver = XForwardedRemoteAddressResolver
+    .maxTrustedIndexXForwardedRemoteAddressResolver(1);
+
+...
+
+.route("direct-route",
+    r -> r.remoteAddr("10.1.1.1", "10.10.1.1/24")
+        .uri("https://downstream1")
+.route("proxied-route",
+    r -> r.remoteAddr(resolver,  "10.10.1.1", "10.10.1.1/24")
+        .uri("https://downstream2")
+)

5. GatewayFilter Factories

Route filters allow the modification of the incoming HTTP request or outgoing HTTP response in some manner. Route filters are scoped to a particular route. Spring Cloud Gateway includes many built-in GatewayFilter Factories.

5.1 AddRequestHeader GatewayFilter Factory

The AddRequestHeader GatewayFilter Factory takes a name and value parameter.

application.yml. 

spring:
   cloud:
     gateway:
diff --git a/spring-cloud-gateway.xml b/spring-cloud-gateway.xml
index 000ada4b..c4ddf9d5 100644
--- a/spring-cloud-gateway.xml
+++ b/spring-cloud-gateway.xml
@@ -232,7 +232,7 @@ for details on setting up your build system with the current Spring Cloud Releas
 
 
RemoteAddr Route Predicate Factory -The RemoteAddr Route Predicate Factory takes a list (min size 1) of CIDR-notation (IPv4 or IPv6) strings, e.g. 192.168.0.1/16 (where 192.168.0.1 is an IP address and 16 is a subnet mask. +The RemoteAddr Route Predicate Factory takes a list (min size 1) of CIDR-notation (IPv4 or IPv6) strings, e.g. 192.168.0.1/16 (where 192.168.0.1 is an IP address and 16 is a subnet mask). application.yml @@ -247,9 +247,73 @@ for details on setting up your build system with the current Spring Cloud Releas This route would match if the remote address of the request was, for example, 192.168.1.10. +
+Modifying the way remote addresses are resolved +By default the RemoteAddr Route Predicate Factory uses the remote address from the incoming request. +This may not match the actual client IP address if Spring Cloud Gateway sits behind a proxy layer. +You can customize the way that the remote address is resolved by setting a custom RemoteAddressResolver. +Spring Cloud Gateway comes with one non-default remote address resolver which is based off of the X-Forwarded-For header, XForwardedRemoteAddressResolver. +XForwardedRemoteAddressResolver has two static constructor methods which take different approaches to security: +XForwardedRemoteAddressResolver::trustAllXForwardedRemoteAddressResolver returns a RemoteAddressResolver which always takes the first IP address found in the X-Forwarded-For header. +This approach is vulnerable to spoofing, as a malicious client could set an initial value for the X-Forwarded-For which would be accepted by the resolver. +XForwardedRemoteAddressResolver::maxTrustedIndexXForwardedRemoteAddressResolver takes an index which correlates to the number of trusted infrastructure running in front of Spring Cloud Gateway. +If Spring Cloud Gateway is, for example only accessible via HAProxy, then a value of 1 should be used. +If two hops of trusted infrastructure are required before Spring Cloud Gateway is accessible, then a value of 2 should be used. +Given the following header value: +X-Forwarded-For: 0.0.0.1, 0.0.0.2, 0.0.0.3 +The maxTrustedIndex values below will yield the following remote addresses. + + + + + + +maxTrustedIndex +result + + + + +[Integer.MIN_VALUE,0] +(invalid, IllegalArgumentException during initialization) + + +1 +0.0.0.3 + + +2 +0.0.0.2 + + +3 +0.0.0.1 + + +[4, Integer.MAX_VALUE] +0.0.0.1 + + + + +Using Java config: +GatewayConfig.java +RemoteAddressResolver resolver = XForwardedRemoteAddressResolver + .maxTrustedIndexXForwardedRemoteAddressResolver(1); + +... + +.route("direct-route", + r -> r.remoteAddr("10.1.1.1", "10.10.1.1/24") + .uri("https://downstream1") +.route("proxied-route", + r -> r.remoteAddr(resolver, "10.10.1.1", "10.10.1.1/24") + .uri("https://downstream2") +) +
- + GatewayFilter Factories Route filters allow the modification of the incoming HTTP request or outgoing HTTP response in some manner. Route filters are scoped to a particular route. Spring Cloud Gateway includes many built-in GatewayFilter Factories.