From edbb3f12aa135dcc3523506ee6b007303504f5be Mon Sep 17 00:00:00 2001 From: buildmaster Date: Thu, 26 Jul 2018 15:17:25 +0000 Subject: [PATCH] Sync docs from master to gh-pages --- multi/multi__actuator_api.html | 2 +- ...e_gateway_using_spring_mvc_or_webflux.html | 4 +- multi/multi__configuration.html | 6 +-- multi/multi__cors_configuration.html | 4 +- multi/multi__developer_guide.html | 4 +- multi/multi__global_filters.html | 4 +- multi/multi__tls_ssl.html | 27 ++++++++++++ multi/multi_spring-cloud-gateway.html | 2 +- single/spring-cloud-gateway.html | 36 +++++++++++++--- spring-cloud-gateway.xml | 42 +++++++++++++++++++ 10 files changed, 112 insertions(+), 19 deletions(-) create mode 100644 multi/multi__tls_ssl.html diff --git a/multi/multi__actuator_api.html b/multi/multi__actuator_api.html index 1bec8a09..62b738b6 100644 --- a/multi/multi__actuator_api.html +++ b/multi/multi__actuator_api.html @@ -1,3 +1,3 @@ - 9. Actuator API

9. Actuator API

TODO: document the /gateway actuator endpoint

\ No newline at end of file + 10. Actuator API

10. Actuator API

TODO: document the /gateway actuator endpoint

\ No newline at end of file diff --git a/multi/multi__building_a_simple_gateway_using_spring_mvc_or_webflux.html b/multi/multi__building_a_simple_gateway_using_spring_mvc_or_webflux.html index 392add7c..f7afdb48 100644 --- a/multi/multi__building_a_simple_gateway_using_spring_mvc_or_webflux.html +++ b/multi/multi__building_a_simple_gateway_using_spring_mvc_or_webflux.html @@ -1,6 +1,6 @@ - 11. Building a Simple Gateway Using Spring MVC or Webflux

11. Building a Simple Gateway Using Spring MVC or Webflux

Spring Cloud Gateway provides a utility object called ProxyExchange which you can use inside a regular Spring web handler as a method parameter. It supports basic downstream HTTP exchanges via methods that mirror the HTTP verbs. With MVC it also supports forwarding to a local handler via the forward() method. To use the ProxyExchange just include the right module in your classpath (either spring-cloud-gateway-mvc or spring-cloud-gateway-webflux).

MVC example (proxying a request to "/test" downstream to a remote server):

@RestController
+   12. Building a Simple Gateway Using Spring MVC or Webflux

12. Building a Simple Gateway Using Spring MVC or Webflux

Spring Cloud Gateway provides a utility object called ProxyExchange which you can use inside a regular Spring web handler as a method parameter. It supports basic downstream HTTP exchanges via methods that mirror the HTTP verbs. With MVC it also supports forwarding to a local handler via the forward() method. To use the ProxyExchange just include the right module in your classpath (either spring-cloud-gateway-mvc or spring-cloud-gateway-webflux).

MVC example (proxying a request to "/test" downstream to a remote server):

@RestController
 @SpringBootApplication
 public class GatewaySampleApplication {
 
@@ -28,4 +28,4 @@
 public ResponseEntity<?> proxyPath(ProxyExchange<byte[]> proxy) throws Exception {
   String path = proxy.path("/proxy/path/");
   return proxy.uri(home.toString() + "/foos/" + path).get();
-}

All the features of Spring MVC or Webflux are available to Gateway handler methods. So you can inject request headers and query parameters, for instance, and you can constrain the incoming requests with declarations in the mapping annotation. See the documentation for @RequestMapping in Spring MVC for more details of those features.

Headers can be added to the downstream response using the header() methods on ProxyExchange.

You can also manipulate response headers (and anything else you like in the response) by adding a mapper to the get() etc. method. The mapper is a Function that takes the incoming ResponseEntity and converts it to an outgoing one.

First class support is provided for "sensitive" headers ("cookie" and "authorization" by default) which are not passed downstream, and for "proxy" headers (x-forwarded-*).

\ No newline at end of file +}

All the features of Spring MVC or Webflux are available to Gateway handler methods. So you can inject request headers and query parameters, for instance, and you can constrain the incoming requests with declarations in the mapping annotation. See the documentation for @RequestMapping in Spring MVC for more details of those features.

Headers can be added to the downstream response using the header() methods on ProxyExchange.

You can also manipulate response headers (and anything else you like in the response) by adding a mapper to the get() etc. method. The mapper is a Function that takes the incoming ResponseEntity and converts it to an outgoing one.

First class support is provided for "sensitive" headers ("cookie" and "authorization" by default) which are not passed downstream, and for "proxy" headers (x-forwarded-*).

\ No newline at end of file diff --git a/multi/multi__configuration.html b/multi/multi__configuration.html index 109fa99f..4aa126ac 100644 --- a/multi/multi__configuration.html +++ b/multi/multi__configuration.html @@ -1,6 +1,6 @@ - 7. Configuration

7. Configuration

Configuration for Spring Cloud Gateway is driven by a collection of `RouteDefinitionLocator`s.

RouteDefinitionLocator.java.  + 8. Configuration

8. Configuration

Configuration for Spring Cloud Gateway is driven by a collection of `RouteDefinitionLocator`s.

RouteDefinitionLocator.java. 

public interface RouteDefinitionLocator {
 	Flux<RouteDefinition> getRouteDefinitions();
 }

@@ -19,7 +19,7 @@ uri: http://example.org filters: - SetStatus=401

-

For some usages of the gateway, properties will be adequate, but some production use cases will benefit from loading configuration from an external source, such as a database. Future milestone versions will have RouteDefinitionLocator implementations based off of Spring Data Repositories such as: Redis, MongoDB and Cassandra.

7.1 Fluent Java Routes API

To allow for simple configuration in Java, there is a fluent API defined in the RouteLocatorBuilder bean.

GatewaySampleApplication.java.  +

For some usages of the gateway, properties will be adequate, but some production use cases will benefit from loading configuration from an external source, such as a database. Future milestone versions will have RouteDefinitionLocator implementations based off of Spring Data Repositories such as: Redis, MongoDB and Cassandra.

8.1 Fluent Java Routes API

To allow for simple configuration in Java, there is a fluent API defined in the RouteLocatorBuilder bean.

GatewaySampleApplication.java. 

// static imports from GatewayFilters and RoutePredicates
 @Bean
 public RouteLocator customRouteLocator(RouteLocatorBuilder builder, ThrottleGatewayFilterFactory throttle) {
@@ -44,4 +44,4 @@
             )
             .build();
 }

-

This style also allows for more custom predicate assertions. The predicates defined by RouteDefinitionLocator beans are combined using logical and. By using the fluent Java API, you can use the and(), or() and negate() operators on the Predicate class.

7.2 DiscoveryClient Route Definition Locator

The Gateway can be configured to create routes based on services registered with a DiscoveryClient compatible service registry.

To enable this, set spring.cloud.gateway.discovery.locator.enabled=true and make sure a DiscoveryClient implementation is on the classpath and enabled (such as Netflix Eureka, Consul or Zookeeper).

\ No newline at end of file +

This style also allows for more custom predicate assertions. The predicates defined by RouteDefinitionLocator beans are combined using logical and. By using the fluent Java API, you can use the and(), or() and negate() operators on the Predicate class.

8.2 DiscoveryClient Route Definition Locator

The Gateway can be configured to create routes based on services registered with a DiscoveryClient compatible service registry.

To enable this, set spring.cloud.gateway.discovery.locator.enabled=true and make sure a DiscoveryClient implementation is on the classpath and enabled (such as Netflix Eureka, Consul or Zookeeper).

\ No newline at end of file diff --git a/multi/multi__cors_configuration.html b/multi/multi__cors_configuration.html index d8275075..f86c1723 100644 --- a/multi/multi__cors_configuration.html +++ b/multi/multi__cors_configuration.html @@ -1,6 +1,6 @@ - 8. CORS Configuration

8. CORS Configuration

The gateway can be configured to control CORS behavior. The "global" CORS configuration is a map of URL patterns to Spring Framework CorsConfiguration.

application.yml.  + 9. CORS Configuration

9. CORS Configuration

The gateway can be configured to control CORS behavior. The "global" CORS configuration is a map of URL patterns to Spring Framework CorsConfiguration.

application.yml. 

spring:
   cloud:
     gateway:
@@ -10,4 +10,4 @@
             allowedOrigins: "docs.spring.io"
             allowedMethods:
             - GET

-

In the example above, CORS requests will be allowed from requests that originate from docs.spring.io for all GET requested paths.

\ No newline at end of file +

In the example above, CORS requests will be allowed from requests that originate from docs.spring.io for all GET requested paths.

\ No newline at end of file diff --git a/multi/multi__developer_guide.html b/multi/multi__developer_guide.html index 60cfc995..be03d6bf 100644 --- a/multi/multi__developer_guide.html +++ b/multi/multi__developer_guide.html @@ -1,6 +1,6 @@ - 10. Developer Guide

10. Developer Guide

TODO: overview of writing custom integrations

10.1 Writing Custom Route Predicate Factories

TODO: document writing Custom Route Predicate Factories

10.2 Writing Custom GatewayFilter Factories

In order to write a GatewayFilter you will need to implement GatewayFilterFactory. There is an abstract class called AbstractGatewayFilterFactory which you can extend.

PreGatewayFilterFactory.java.  + 11. Developer Guide

11. Developer Guide

TODO: overview of writing custom integrations

11.1 Writing Custom Route Predicate Factories

TODO: document writing Custom Route Predicate Factories

11.2 Writing Custom GatewayFilter Factories

In order to write a GatewayFilter you will need to implement GatewayFilterFactory. There is an abstract class called AbstractGatewayFilterFactory which you can extend.

PreGatewayFilterFactory.java. 

public class PreGatewayFilterFactory extends AbstractGatewayFilterFactory<PreGatewayFilterFactory.Config> {
 
 	public PreGatewayFilterFactory() {
@@ -47,4 +47,4 @@
 	}
 
 }

-

10.3 Writing Custom Global Filters

TODO: document writing Custom Global Filters

10.4 Writing Custom Route Locators and Writers

TODO: document writing Custom Route Locators and Writers

\ No newline at end of file +

11.3 Writing Custom Global Filters

TODO: document writing Custom Global Filters

11.4 Writing Custom Route Locators and Writers

TODO: document writing Custom Route Locators and Writers

\ No newline at end of file diff --git a/multi/multi__global_filters.html b/multi/multi__global_filters.html index 907421ed..0ef07328 100644 --- a/multi/multi__global_filters.html +++ b/multi/multi__global_filters.html @@ -1,6 +1,6 @@ - 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

When a request comes in (and matches a Route) the Filtering Web Handler will add all instances of GlobalFilter and all route specific instances of GatewayFilter to a filter chain. This combined filter chain is sorted by the org.springframework.core.Ordered interface, which can be set by implementing the getOrder() method or by using the @Order annotation.

As Spring Cloud Gateway distinguishes between "pre" and "post" phases for filter logic execution (see: How It Works), the filter with the highest precedence will be the first in the "pre"-phase and the last in the "post"-phase.

ExampleConfiguration.java.  + 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

When a request comes in (and matches a Route) the Filtering Web Handler will add all instances of GlobalFilter and all route specific instances of GatewayFilter to a filter chain. This combined filter chain is sorted by the org.springframework.core.Ordered interface, which can be set by implementing the getOrder() method or by using the @Order annotation.

As Spring Cloud Gateway distinguishes between "pre" and "post" phases for filter logic execution (see: How It Works), the filter with the highest precedence will be the first in the "pre"-phase and the last in the "post"-phase.

ExampleConfiguration.java. 

@Bean
 @Order(-1)
 public GlobalFilter a() {
@@ -60,4 +60,4 @@
 

6.8 Gateway Metrics Filter

The Gateway Metrics Filter runs as long as the property spring.cloud.gateway.metrics.enabled is not set to false. This filter adds a timer metric named "gateway.requests" with the following tags:

  • routeId: The route id
  • routeUri: The URI that the API will be routed to
  • outcome |Outcome as classified by HttpStatus.Series
  • status: Http Status of the request returned to the client

These metrics are then available to be scraped from /actuator/metrics/gateway.requests and can be easily integated with Prometheus to create a Grafana dashboard.

6.9 Making An Exchange As Routed

After the Gateway has routed a ServerWebExchange it will mark that exchange as "routed" by adding gatewayAlreadyRouted to the exchange attributes. Once a request has been marked as routed, other routing filters will not route the request again, essentially skipping the filter. There are convenience methods that you can use to mark an exchange as routed -or check if an exchange has already been routed.

  • ServerWebExchangeUtils.isAlreadyRouted takes a ServerWebExchange object and checks if it has been "routed"
  • ServerWebExchangeUtils.setAlreadyRouted takes a ServerWebExchange object and marks it as "routed"
\ No newline at end of file +or check if an exchange has already been routed.

  • ServerWebExchangeUtils.isAlreadyRouted takes a ServerWebExchange object and checks if it has been "routed"
  • ServerWebExchangeUtils.setAlreadyRouted takes a ServerWebExchange object and marks it as "routed"
\ No newline at end of file diff --git a/multi/multi__tls_ssl.html b/multi/multi__tls_ssl.html new file mode 100644 index 00000000..79f9863d --- /dev/null +++ b/multi/multi__tls_ssl.html @@ -0,0 +1,27 @@ + + + 7. TLS / SSL

7. TLS / SSL

The Gateway can listen for requests on https by following the usual Spring server configuration. Example:

application.yml.  +

server:
+  ssl:
+    enabled: true
+    key-alias: scg
+    key-store-password: scg1234
+    key-store: classpath:scg-keystore.p12
+    key-store-type: PKCS12

+

Gateway routes can be routed to both http and https backends. If routing to a https backend then the Gateway can be configured to trust all downstream certificates with the following configuration:

application.yml.  +

spring:
+  cloud:
+    gateway:
+      httpclient:
+        ssl:
+          useInsecureTrustManager: true

+

Using an insecure trust manager is not suitable for production. For a production deployment the Gateway can be configured with a set of known certificates that it can trust with the follwing configuration:

application.yml.  +

spring:
+  cloud:
+    gateway:
+      httpclient:
+        ssl:
+          trustedX509Certificates:
+          - cert1.pem
+          - cert2.pem

+

\ No newline at end of file diff --git a/multi/multi_spring-cloud-gateway.html b/multi/multi_spring-cloud-gateway.html index eae56261..c519e1e4 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
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.7.1. Redis RateLimiter
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
5.19. Retry 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
6.8. Gateway Metrics Filter
6.9. Making An Exchange As Routed
7. Configuration
7.1. Fluent Java Routes API
7.2. DiscoveryClient Route Definition Locator
8. CORS Configuration
9. Actuator API
10. Developer Guide
10.1. Writing Custom Route Predicate Factories
10.2. Writing Custom GatewayFilter Factories
10.3. Writing Custom Global Filters
10.4. Writing Custom Route Locators and Writers
11. Building a Simple Gateway Using Spring MVC or Webflux
\ 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.7.1. Redis RateLimiter
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
5.19. Retry 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
6.8. Gateway Metrics Filter
6.9. Making An Exchange As Routed
7. TLS / SSL
8. Configuration
8.1. Fluent Java Routes API
8.2. DiscoveryClient Route Definition Locator
9. CORS Configuration
10. Actuator API
11. Developer Guide
11.1. Writing Custom Route Predicate Factories
11.2. Writing Custom GatewayFilter Factories
11.3. Writing Custom Global Filters
11.4. Writing Custom Route Locators and Writers
12. Building a Simple Gateway Using Spring MVC or Webflux
\ No newline at end of file diff --git a/single/spring-cloud-gateway.html b/single/spring-cloud-gateway.html index 13925ebe..75e8777c 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
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.7.1. Redis RateLimiter
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
5.19. Retry 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
6.8. Gateway Metrics Filter
6.9. Making An Exchange As Routed
7. Configuration
7.1. Fluent Java Routes API
7.2. DiscoveryClient Route Definition Locator
8. CORS Configuration
9. Actuator API
10. Developer Guide
10.1. Writing Custom Route Predicate Factories
10.2. Writing Custom GatewayFilter Factories
10.3. Writing Custom Global Filters
10.4. Writing Custom Route Locators and Writers
11. Building a Simple Gateway Using Spring MVC or Webflux

2.0.1.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.7.1. Redis RateLimiter
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
5.19. Retry 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
6.8. Gateway Metrics Filter
6.9. Making An Exchange As Routed
7. TLS / SSL
8. Configuration
8.1. Fluent Java Routes API
8.2. DiscoveryClient Route Definition Locator
9. CORS Configuration
10. Actuator API
11. Developer Guide
11.1. Writing Custom Route Predicate Factories
11.2. Writing Custom GatewayFilter Factories
11.3. Writing Custom Global Filters
11.4. Writing Custom Route Locators and Writers
12. Building a Simple Gateway Using Spring MVC or Webflux

2.0.1.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:
@@ -393,7 +393,31 @@ using something like 

6.8 Gateway Metrics Filter

The Gateway Metrics Filter runs as long as the property spring.cloud.gateway.metrics.enabled is not set to false. This filter adds a timer metric named "gateway.requests" with the following tags:

  • routeId: The route id
  • routeUri: The URI that the API will be routed to
  • outcome |Outcome as classified by HttpStatus.Series
  • status: Http Status of the request returned to the client

These metrics are then available to be scraped from /actuator/metrics/gateway.requests and can be easily integated with Prometheus to create a Grafana dashboard.

6.9 Making An Exchange As Routed

After the Gateway has routed a ServerWebExchange it will mark that exchange as "routed" by adding gatewayAlreadyRouted to the exchange attributes. Once a request has been marked as routed, other routing filters will not route the request again, essentially skipping the filter. There are convenience methods that you can use to mark an exchange as routed -or check if an exchange has already been routed.

  • ServerWebExchangeUtils.isAlreadyRouted takes a ServerWebExchange object and checks if it has been "routed"
  • ServerWebExchangeUtils.setAlreadyRouted takes a ServerWebExchange object and marks it as "routed"

7. Configuration

Configuration for Spring Cloud Gateway is driven by a collection of `RouteDefinitionLocator`s.

RouteDefinitionLocator.java.  +or check if an exchange has already been routed.

  • ServerWebExchangeUtils.isAlreadyRouted takes a ServerWebExchange object and checks if it has been "routed"
  • ServerWebExchangeUtils.setAlreadyRouted takes a ServerWebExchange object and marks it as "routed"

7. TLS / SSL

The Gateway can listen for requests on https by following the usual Spring server configuration. Example:

application.yml.  +

server:
+  ssl:
+    enabled: true
+    key-alias: scg
+    key-store-password: scg1234
+    key-store: classpath:scg-keystore.p12
+    key-store-type: PKCS12

+

Gateway routes can be routed to both http and https backends. If routing to a https backend then the Gateway can be configured to trust all downstream certificates with the following configuration:

application.yml.  +

spring:
+  cloud:
+    gateway:
+      httpclient:
+        ssl:
+          useInsecureTrustManager: true

+

Using an insecure trust manager is not suitable for production. For a production deployment the Gateway can be configured with a set of known certificates that it can trust with the follwing configuration:

application.yml.  +

spring:
+  cloud:
+    gateway:
+      httpclient:
+        ssl:
+          trustedX509Certificates:
+          - cert1.pem
+          - cert2.pem

+

8. Configuration

Configuration for Spring Cloud Gateway is driven by a collection of `RouteDefinitionLocator`s.

RouteDefinitionLocator.java. 

public interface RouteDefinitionLocator {
 	Flux<RouteDefinition> getRouteDefinitions();
 }

@@ -412,7 +436,7 @@ or check if an exchange has already been routed.

uri: http://example.org filters: - SetStatus=401

-

For some usages of the gateway, properties will be adequate, but some production use cases will benefit from loading configuration from an external source, such as a database. Future milestone versions will have RouteDefinitionLocator implementations based off of Spring Data Repositories such as: Redis, MongoDB and Cassandra.

7.1 Fluent Java Routes API

To allow for simple configuration in Java, there is a fluent API defined in the RouteLocatorBuilder bean.

GatewaySampleApplication.java.  +

For some usages of the gateway, properties will be adequate, but some production use cases will benefit from loading configuration from an external source, such as a database. Future milestone versions will have RouteDefinitionLocator implementations based off of Spring Data Repositories such as: Redis, MongoDB and Cassandra.

8.1 Fluent Java Routes API

To allow for simple configuration in Java, there is a fluent API defined in the RouteLocatorBuilder bean.

GatewaySampleApplication.java. 

// static imports from GatewayFilters and RoutePredicates
 @Bean
 public RouteLocator customRouteLocator(RouteLocatorBuilder builder, ThrottleGatewayFilterFactory throttle) {
@@ -437,7 +461,7 @@ or check if an exchange has already been routed.

-

This style also allows for more custom predicate assertions. The predicates defined by RouteDefinitionLocator beans are combined using logical and. By using the fluent Java API, you can use the and(), or() and negate() operators on the Predicate class.

7.2 DiscoveryClient Route Definition Locator

The Gateway can be configured to create routes based on services registered with a DiscoveryClient compatible service registry.

To enable this, set spring.cloud.gateway.discovery.locator.enabled=true and make sure a DiscoveryClient implementation is on the classpath and enabled (such as Netflix Eureka, Consul or Zookeeper).

8. CORS Configuration

The gateway can be configured to control CORS behavior. The "global" CORS configuration is a map of URL patterns to Spring Framework CorsConfiguration.

application.yml.  +

This style also allows for more custom predicate assertions. The predicates defined by RouteDefinitionLocator beans are combined using logical and. By using the fluent Java API, you can use the and(), or() and negate() operators on the Predicate class.

8.2 DiscoveryClient Route Definition Locator

The Gateway can be configured to create routes based on services registered with a DiscoveryClient compatible service registry.

To enable this, set spring.cloud.gateway.discovery.locator.enabled=true and make sure a DiscoveryClient implementation is on the classpath and enabled (such as Netflix Eureka, Consul or Zookeeper).

9. CORS Configuration

The gateway can be configured to control CORS behavior. The "global" CORS configuration is a map of URL patterns to Spring Framework CorsConfiguration.

application.yml. 

spring:
   cloud:
     gateway:
@@ -447,7 +471,7 @@ or check if an exchange has already been routed.

allowedOrigins: "docs.spring.io" allowedMethods: - GET

-

In the example above, CORS requests will be allowed from requests that originate from docs.spring.io for all GET requested paths.

9. Actuator API

TODO: document the /gateway actuator endpoint

10. Developer Guide

TODO: overview of writing custom integrations

10.1 Writing Custom Route Predicate Factories

TODO: document writing Custom Route Predicate Factories

10.2 Writing Custom GatewayFilter Factories

In order to write a GatewayFilter you will need to implement GatewayFilterFactory. There is an abstract class called AbstractGatewayFilterFactory which you can extend.

PreGatewayFilterFactory.java.  +

In the example above, CORS requests will be allowed from requests that originate from docs.spring.io for all GET requested paths.

10. Actuator API

TODO: document the /gateway actuator endpoint

11. Developer Guide

TODO: overview of writing custom integrations

11.1 Writing Custom Route Predicate Factories

TODO: document writing Custom Route Predicate Factories

11.2 Writing Custom GatewayFilter Factories

In order to write a GatewayFilter you will need to implement GatewayFilterFactory. There is an abstract class called AbstractGatewayFilterFactory which you can extend.

PreGatewayFilterFactory.java. 

public class PreGatewayFilterFactory extends AbstractGatewayFilterFactory<PreGatewayFilterFactory.Config> {
 
 	public PreGatewayFilterFactory() {
@@ -494,7 +518,7 @@ or check if an exchange has already been routed.

-

10.3 Writing Custom Global Filters

TODO: document writing Custom Global Filters

10.4 Writing Custom Route Locators and Writers

TODO: document writing Custom Route Locators and Writers

11. Building a Simple Gateway Using Spring MVC or Webflux

Spring Cloud Gateway provides a utility object called ProxyExchange which you can use inside a regular Spring web handler as a method parameter. It supports basic downstream HTTP exchanges via methods that mirror the HTTP verbs. With MVC it also supports forwarding to a local handler via the forward() method. To use the ProxyExchange just include the right module in your classpath (either spring-cloud-gateway-mvc or spring-cloud-gateway-webflux).

MVC example (proxying a request to "/test" downstream to a remote server):

@RestController
+

11.3 Writing Custom Global Filters

TODO: document writing Custom Global Filters

11.4 Writing Custom Route Locators and Writers

TODO: document writing Custom Route Locators and Writers

12. Building a Simple Gateway Using Spring MVC or Webflux

Spring Cloud Gateway provides a utility object called ProxyExchange which you can use inside a regular Spring web handler as a method parameter. It supports basic downstream HTTP exchanges via methods that mirror the HTTP verbs. With MVC it also supports forwarding to a local handler via the forward() method. To use the ProxyExchange just include the right module in your classpath (either spring-cloud-gateway-mvc or spring-cloud-gateway-webflux).

MVC example (proxying a request to "/test" downstream to a remote server):

@RestController
 @SpringBootApplication
 public class GatewaySampleApplication {
 
diff --git a/spring-cloud-gateway.xml b/spring-cloud-gateway.xml
index af8e6b2c..845dade2 100644
--- a/spring-cloud-gateway.xml
+++ b/spring-cloud-gateway.xml
@@ -980,6 +980,48 @@ or check if an exchange has already been routed.
 
 
 
+
+TLS / SSL
+The Gateway can listen for requests on https by following the usual Spring server configuration. Example:
+
+application.yml
+
+server:
+  ssl:
+    enabled: true
+    key-alias: scg
+    key-store-password: scg1234
+    key-store: classpath:scg-keystore.p12
+    key-store-type: PKCS12
+
+
+Gateway routes can be routed to both http and https backends. If routing to a https backend then the Gateway can be configured to trust all downstream certificates with the following configuration:
+
+application.yml
+
+spring:
+  cloud:
+    gateway:
+      httpclient:
+        ssl:
+          useInsecureTrustManager: true
+
+
+Using an insecure trust manager is not suitable for production. For a production deployment the Gateway can be configured with a set of known certificates that it can trust with the follwing configuration:
+
+application.yml
+
+spring:
+  cloud:
+    gateway:
+      httpclient:
+        ssl:
+          trustedX509Certificates:
+          - cert1.pem
+          - cert2.pem
+
+
+
 
 Configuration
 Configuration for Spring Cloud Gateway is driven by a collection of `RouteDefinitionLocator`s.