### POST /actuator/gateway/refresh with metadata example routes Source: https://github.com/spring-cloud/spring-cloud-gateway/blob/main/docs/modules/ROOT/pages/spring-cloud-gateway-server-webflux/actuator-api.adoc Example route definitions showing routes with metadata group:group-1 and group:group-2, used to illustrate the metadata-based refresh. ```json [{ "route_id": "first_route", "route_object": { "predicate": "...", }, "metadata": { "group": "group-1" } }, { "route_id": "second_route", "route_object": { "predicate": "...", }, "metadata": { "group": "group-2" } }, { "route_id": "third_route", "route_object": { "predicate": "...", }, "metadata": { "group": "group-1" } }] ``` -------------------------------- ### X-Forwarded-For Header Example Source: https://github.com/spring-cloud/spring-cloud-gateway/blob/main/docs/modules/ROOT/pages/spring-cloud-gateway-server-webflux/request-predicates-factories.adoc Shows an example X-Forwarded-For header value used to illustrate how maxTrustedIndex affects remote address resolution. ```text X-Forwarded-For: 0.0.0.1, 0.0.0.2, 0.0.0.3 ``` -------------------------------- ### Compare Retry GatewayFilter standard and shortcut notation Source: https://github.com/spring-cloud/spring-cloud-gateway/blob/main/docs/modules/ROOT/pages/spring-cloud-gateway-server-webflux/gatewayfilter-factories/retry-factory.adoc This example shows the equivalence between the standard verbose configuration and the simplified shortcut notation for the Retry filter. ```yaml spring: cloud: gateway: server: webflux: routes: - id: retry_route uri: https://example.org filters: - name: Retry args: retries: 3 statuses: INTERNAL_SERVER_ERROR methods: GET backoff: firstBackoff: 10ms maxBackoff: 50ms factor: 2 basedOnPreviousValue: false jitter: randomFactor: 0.5 timeout: 100ms - id: retryshortcut_route uri: https://example.org filters: - Retry=3,INTERNAL_SERVER_ERROR,GET,10ms,50ms,2,false,0.5,100ms ``` -------------------------------- ### Path Request Predicate Configuration Source: https://github.com/spring-cloud/spring-cloud-gateway/blob/main/docs/modules/ROOT/pages/spring-cloud-gateway-server-webmvc/gateway-request-predicates.adoc Examples of configuring a path-based route predicate using YAML and Java DSL. ```yaml spring: cloud: gateway: server: webmvc: routes: - id: path_route uri: https://example.org predicates: - Path=/red/{segment},/blue/{segment} ``` ```java import static org.springframework.cloud.gateway.server.mvc.filter.BeforeFilterFunctions.uri; import static org.springframework.cloud.gateway.server.mvc.handler.GatewayRouterFunctions.route; import static org.springframework.cloud.gateway.server.mvc.handler.HandlerFunctions.http; import static org.springframework.cloud.gateway.server.mvc.predicate.GatewayRequestPredicates.path; @Configuration class RouteConfiguration { @Bean public RouterFunction gatewayRouterFunctionsPath() { return route("path_route") .route(path("/red/{segment}", "/blue/{segment}"), http()) .before(uri("https://example.org")) .build(); } } ``` -------------------------------- ### Basic route with RouterFunctions.route() Source: https://github.com/spring-cloud/spring-cloud-gateway/blob/main/docs/modules/ROOT/pages/spring-cloud-gateway-server-webmvc/java-routes-api.adoc Creates a simple route that proxies GET /get to https://example.org using RouterFunctions.route() and HandlerFunctions.http(). The route uses the before filter to set the downstream URI. ```java import static org.springframework.web.servlet.function.RouterFunctions.route; import static org.springframework.cloud.gateway.server.mvc.filter.BeforeFilterFunctions.uri; import static org.springframework.cloud.gateway.server.mvc.handler.HandlerFunctions.http; class SimpleGateway { @Bean public RouterFunction getRoute() { return route().GET("/get", http()) .before(uri("https://example.org")) .build(); } } ``` -------------------------------- ### GET /actuator/gateway/routes/{id} response Source: https://github.com/spring-cloud/spring-cloud-gateway/blob/main/docs/modules/ROOT/pages/spring-cloud-gateway-server-webflux/actuator-api.adoc Example JSON response for a single route, showing the route_id, predicate as a single string, filters, URI, and order. ```json { "route_id": "first_route", "predicate": "(Paths: [/first], match trailing slash: true)", "filters": [], "uri": "https://www.uri-destination.org", "order": 0 } ``` -------------------------------- ### Define routes with RouteLocatorBuilder Source: https://github.com/spring-cloud/spring-cloud-gateway/blob/main/docs/modules/ROOT/pages/spring-cloud-gateway-server-webflux/fluent-java-routes-api.adoc This example demonstrates how to use the RouteLocatorBuilder bean to define multiple routes with specific hosts, paths, filters, and metadata in GatewaySampleApplication.java. ```java // static imports from GatewayFilters and RoutePredicates @Bean public RouteLocator customRouteLocator(RouteLocatorBuilder builder, ThrottleGatewayFilterFactory throttle) { return builder.routes() .route(r -> r.host("**.abc.org").and().path("/image/png") .filters(f -> f.addResponseHeader("X-TestHeader", "foobar")) .uri("http://httpbin.org:80") ) .route(r -> r.path("/image/webp") .filters(f -> f.addResponseHeader("X-AnotherHeader", "baz")) .uri("http://httpbin.org:80") .metadata("key", "value") ) .route(r -> r.order(-1) .host("**.throttle.org").and().path("/get") .filters(f -> f.filter(throttle.apply(1, 1, 10, TimeUnit.SECONDS))) .uri("http://httpbin.org:80") .metadata("key", "value") ) .build(); } ``` -------------------------------- ### GET /actuator/gateway/routes response Source: https://github.com/spring-cloud/spring-cloud-gateway/blob/main/docs/modules/ROOT/pages/spring-cloud-gateway-server-webflux/actuator-api.adoc Example verbose JSON response from the routes endpoint, showing route details including predicates, filters, URI, and order. ```json [{ "predicate": "Paths: [/first], match trailing slash: true", "route_id": "first_route", "filters": [ "[[PreserveHostHeader], order = 0]" ], "uri": "https://www.uri-destination.org", "order": 0 }, { "predicate": "Paths: [/second], match trailing slash: true", "route_id": "second_route", "filters": [], "uri": "https://www.uri-destination.org", "order": 0 }] ``` -------------------------------- ### Configure DiscoveryClient routes in application.yml Source: https://github.com/spring-cloud/spring-cloud-gateway/blob/main/docs/modules/ROOT/pages/spring-cloud-gateway-server-webflux/the-discoveryclient-route-definition-locator.adoc Example of defining custom predicates and filters for DiscoveryClient routes using YAML format. Ensure the RewritePath filter is included to avoid downstream 404 errors. ```yaml spring: cloud: gateway: discovery: locator: predicates: - name: Host args: pattern: "'**.foo.com'" - name: Path args: pattern: "'/'+serviceId+'/**'" filters: - name: CircuitBreaker args: name: serviceId - name: RewritePath args: regexp: "'/' + serviceId + '/?(?.*)'" replacement: "'/${remaining}'" ``` -------------------------------- ### RedirectTo Filter Configuration Source: https://github.com/spring-cloud/spring-cloud-gateway/blob/main/docs/modules/ROOT/pages/spring-cloud-gateway-server-webmvc/filters/redirectto.adoc Configuration examples for the RedirectTo filter in both YAML and Java DSL. ```APIDOC ## RedirectTo Filter ### Description The `RedirectTo` filter sends a redirect response with a specified HTTP status code and a `Location` header. It takes two parameters: `status` (a 300 series redirect code) and `url` (a valid URL used as the `Location` header value). ### Configuration #### YAML Configuration ```yaml spring: cloud: gateway: server: webmvc: routes: - id: redirectto_route uri: https://example.org predicates: - Path=/** filters: - RedirectTo=302, https://acme.org ``` #### Java Configuration ```java import static org.springframework.cloud.gateway.server.mvc.filter.BeforeFilterFunctions.uri; import static org.springframework.cloud.gateway.server.mvc.filter.FilterFunctions.redirectTo; import static org.springframework.cloud.gateway.server.mvc.handler.GatewayRouterFunctions.route; import static org.springframework.cloud.gateway.server.mvc.handler.HandlerFunctions.http; @Configuration class RouteConfiguration { @Bean public RouterFunction gatewayRouterFunctionsRedirectTo() { return route("redirectto_route") .GET("/**", http()) .before(uri("https://example.org")) .filter(redirectTo(302, URI.create("acme.org"))) .build(); } } ``` ### Parameters - `status` (integer) - Required - A 300 series redirect HTTP code, such as 301 or 302. - `url` (string) - Required - A valid URL that will be used as the `Location` header value. ### Behavior When a request matches the route, the filter sends a response with the specified status code and a `Location` header set to the provided URL. For relative redirects, use `uri: no://op` as the route's URI. ### Example A configuration with `RedirectTo=302, https://acme.org` will send a status 302 with a `Location: https://acme.org` header to perform a redirect. ``` -------------------------------- ### Enable Permissions-Policy header globally Source: https://github.com/spring-cloud/spring-cloud-gateway/blob/main/docs/modules/ROOT/pages/spring-cloud-gateway-server-webflux/gatewayfilter-factories/secureheaders-factory.adoc YAML configuration to enable the Permissions-Policy header and set its value using the permissions-policy property. The example allows geolocation for the site's own origin and https://example.com. ```yaml spring: cloud: gateway: filter: secure-headers: enable: permissions-policy permissions-policy : geolocation=(self "https://example.com") ``` -------------------------------- ### Configure DiscoveryClient routes in application.properties Source: https://github.com/spring-cloud/spring-cloud-gateway/blob/main/docs/modules/ROOT/pages/spring-cloud-gateway-server-webflux/the-discoveryclient-route-definition-locator.adoc Example of defining custom predicates and filters for DiscoveryClient routes using properties format. Note that custom filters replace the default list, so RewritePath must be explicitly included. ```properties spring.cloud.gateway.discovery.locator.predicates[0].name=Path spring.cloud.gateway.discovery.locator.predicates[0].args[pattern]="'/'+serviceId+'/**'" spring.cloud.gateway.discovery.locator.predicates[1].name=Host spring.cloud.gateway.discovery.locator.predicates[1].args[pattern]="'**.foo.com'" spring.cloud.gateway.discovery.locator.filters[0].name=CircuitBreaker spring.cloud.gateway.discovery.locator.filters[0].args[name]=serviceId spring.cloud.gateway.discovery.locator.filters[1].name=RewritePath spring.cloud.gateway.discovery.locator.filters[1].args[regexp]="'/' + serviceId + '/?(?.*)'" spring.cloud.gateway.discovery.locator.filters[1].args[replacement]="'/\${remaining}'" ``` -------------------------------- ### Configure SetStatus GatewayFilter in application.yml Source: https://github.com/spring-cloud/spring-cloud-gateway/blob/main/docs/modules/ROOT/pages/spring-cloud-gateway-server-webflux/gatewayfilter-factories/setstatus-factory.adoc This example demonstrates configuring the SetStatus filter using both string and integer status representations in a YAML configuration file. ```yaml spring: cloud: gateway: server: webflux: routes: - id: setstatusstring_route uri: https://example.org filters: - SetStatus=UNAUTHORIZED - id: setstatusint_route uri: https://example.org filters: - SetStatus=401 ``` -------------------------------- ### Configure Retry GatewayFilter in application.yml Source: https://github.com/spring-cloud/spring-cloud-gateway/blob/main/docs/modules/ROOT/pages/spring-cloud-gateway-server-webflux/gatewayfilter-factories/retry-factory.adoc This example demonstrates how to configure the Retry filter with specific retry counts, status codes, methods, backoff settings, jitter, and timeouts. ```yaml spring: cloud: gateway: server: webflux: routes: - id: retry_test uri: http://localhost:8080/flakey predicates: - Host=*.retry.com filters: - name: Retry args: retries: 3 statuses: BAD_GATEWAY methods: GET,POST backoff: firstBackoff: 10ms maxBackoff: 50ms factor: 2 basedOnPreviousValue: false jitter: randomFactor: 0.5 timeout: 100ms ``` -------------------------------- ### Fully Expanded Arguments for Cookie Predicate Source: https://github.com/spring-cloud/spring-cloud-gateway/blob/main/docs/modules/ROOT/pages/spring-cloud-gateway-server-webflux/configuring-route-predicate-factories-and-filter-factories.adoc Configures the Cookie Route Predicate Factory using fully expanded arguments with name and args keys. This is the full configuration equivalent to the shortcut example. ```yaml spring: cloud: gateway: server: webflux: routes: - id: after_route uri: https://example.org predicates: - name: Cookie args: name: mycookie regexp: mycookievalue ``` -------------------------------- ### Configure ignoredClassPatterns and ignoredResourcePatterns for duplicate-finder-maven-plugin Source: https://github.com/spring-cloud/spring-cloud-gateway/blob/main/README.adoc Shows how to add ignoredClassPatterns and ignoredResourcePatterns to the plugin configuration section. The example ignores org.joda.time.base.BaseDateTime, .*module-info, and changelog.txt. ```xml org.basepom.maven duplicate-finder-maven-plugin org.joda.time.base.BaseDateTime .*module-info changelog.txt ``` -------------------------------- ### Redis RateLimiter configuration Source: https://github.com/spring-cloud/spring-cloud-gateway/blob/main/docs/modules/ROOT/pages/spring-cloud-gateway-server-webflux/gatewayfilter-factories/requestratelimiter-factory.adoc Configures a redis-rate-limiter with replenishRate, burstCapacity, and requestedTokens. This example allows 10 requests per user with a burst of 20. ```yaml spring: cloud: gateway: server: webflux: routes: - id: requestratelimiter_route uri: https://example.org filters: - name: RequestRateLimiter args: redis-rate-limiter.replenishRate: 10 redis-rate-limiter.burstCapacity: 20 redis-rate-limiter.requestedTokens: 1 ``` -------------------------------- ### Checkstyle directory structure Source: https://github.com/spring-cloud/spring-cloud-gateway/blob/main/README.adoc Shows the layout of the spring-cloud-build-tools module with checkstyle configuration files. The files include checkstyle.xml (default rules), checkstyle-header.txt (file header setup), and checkstyle-suppressions.xml (default suppression rules). ```text └── src ├── checkstyle │ └── checkstyle-suppressions.xml <3> └── main └── resources ├── checkstyle-header.txt <2> └── checkstyle.xml <1> ``` -------------------------------- ### RouterFunctions.route().GET() Source: https://github.com/spring-cloud/spring-cloud-gateway/blob/main/docs/modules/ROOT/pages/spring-cloud-gateway-server-webmvc/java-routes-api.adoc Creates a route using the RouterFunctions.Builder obtained from RouterFunctions.route(). The GET method combines a path predicate with a handler function and can be used with a before filter to set the target URI. ```APIDOC ## [GET] /get ### Description Creates a route that handles GET requests to the specified path and proxies them to the target URI set by the before filter. ### Method GET ### Endpoint /get ### Parameters #### Path Parameters - **path** (string) - Required - The path predicate for the route, e.g., `/get`. ### Request Example No request body required. ### Response #### Success Response (200) - **body** (ServerResponse) - The response from the downstream service. #### Response Example No example provided. ### Notes - The `http()` handler function sends the request to the URI provided by the `uri()` before filter. - The `before(uri("https://example.org"))` filter sets the target URI. ### Code Example ```java import static org.springframework.web.servlet.function.RouterFunctions.route; import static org.springframework.cloud.gateway.server.mvc.filter.BeforeFilterFunctions.uri; import static org.springframework.cloud.gateway.server.mvc.handler.HandlerFunctions.http; class SimpleGateway { @Bean public RouterFunction getRoute() { return route().GET("/get", http()) .before(uri("https://example.org")) .build(); } } ``` ``` -------------------------------- ### Custom PredicateSupplier Implementation Source: https://github.com/spring-cloud/spring-cloud-gateway/blob/main/docs/modules/ROOT/pages/spring-cloud-gateway-server-webmvc/writing-custom-predicates-and-filters.adoc Implements PredicateSupplier to register custom predicates. The get() method returns the static methods of SampleRequestPredicates that return RequestPredicates. ```java package com.example; import org.springframework.cloud.gateway.server.mvc.predicate.PredicateSupplier; class SamplePredicateSupplier implements PredicateSupplier { @Override public Collection get() { return Arrays.asList(SampleRequestPredicates.class.getMethods()); } } ``` -------------------------------- ### Configure RequestSize filter in Java (GatewaySampleApplication.java) Source: https://github.com/spring-cloud/spring-cloud-gateway/blob/main/docs/modules/ROOT/pages/spring-cloud-gateway-server-webmvc/filters/requestsize.adoc Java configuration using the functional API to define a route with the RequestSize filter. It imports static methods from BeforeFilterFunctions and GatewayRouterFunctions. The route handles GET /upload, forwards to http://localhost:8080, and applies requestSize("5000000"). ```java import static org.springframework.cloud.gateway.server.mvc.filter.BeforeFilterFunctions.uri; import static org.springframework.cloud.gateway.server.mvc.filter.BeforeFilterFunctions.requestSize; import static org.springframework.cloud.gateway.server.mvc.handler.GatewayRouterFunctions.route; import static org.springframework.cloud.gateway.server.mvc.handler.HandlerFunctions.http; @Configuration class RouteConfiguration { @Bean public RouterFunction gatewayRouterFunctionsRequestSize() { return route("request_size_route") .GET("/upload", http()) .before(uri("http://localhost:8080")) .before(requestSize("5000000")) .build(); } } ``` -------------------------------- ### Configure bucket4j rate limiter with capacity and refill Source: https://github.com/spring-cloud/spring-cloud-gateway/blob/main/docs/modules/ROOT/pages/spring-cloud-gateway-server-webflux/gatewayfilter-factories/requestratelimiter-factory.adoc Configures a RequestRateLimiter filter with bucket4j properties to allow a burst of 20 requests and refill 10 tokens per second. The example sets capacity, refillTokens, refillPeriod, and requestedTokens; it is noted as not recommended for production. ```yaml spring: cloud: gateway: server: webflux: routes: - id: requestratelimiter_route uri: https://example.org filters: - name: RequestRateLimiter args: bucket4j-rate-limiter.capacity: 20 bucket4j-rate-limiter.refillTokens: 10 bucket4j-rate-limiter.refillPeriod: 1s bucket4j-rate-limiter.requestedTokens: 1 ``` -------------------------------- ### Configure StripContextPath filter in Java Source: https://github.com/spring-cloud/spring-cloud-gateway/blob/main/docs/modules/ROOT/pages/spring-cloud-gateway-server-webmvc/filters/stripcontextpath.adoc Java configuration for the StripContextPath filter using the BeforeFilterFunctions API. It defines a route with GET /name/**, sets the URI to https://example.org, and applies stripContextPath() before stripPrefix(1). ```java import static org.springframework.cloud.gateway.server.mvc.filter.BeforeFilterFunctions.stripContextPath; import static org.springframework.cloud.gateway.server.mvc.filter.BeforeFilterFunctions.stripPrefix; import static org.springframework.cloud.gateway.server.mvc.filter.BeforeFilterFunctions.uri; import static org.springframework.cloud.gateway.server.mvc.handler.GatewayRouterFunctions.route; import static org.springframework.cloud.gateway.server.mvc.handler.HandlerFunctions.http; @Configuration class RouteConfiguration { @Bean public RouterFunction gatewayRouterFunctionsStripContextPath() { return route("strip_context_path_route") .GET("/name/**", http()) .before(uri("https://example.org")) .before(stripContextPath()) .before(stripPrefix(1)) .build(); } } ``` -------------------------------- ### WebFlux Proxy Exchange example: proxy request to /test Source: https://github.com/spring-cloud/spring-cloud-gateway/blob/main/docs/modules/ROOT/pages/spring-cloud-gateway-proxy-exchange.adoc Use this WebFlux controller to proxy a request to /test downstream to a remote server. Requires the spring-cloud-gateway-proxyexchange-webflux module on the classpath. The method returns a Mono> and uses the same ProxyExchange API as the MVC version. ```java @RestController @SpringBootApplication public class GatewaySampleApplication { @Value("${remote.home}") private URI home; @GetMapping("/test") public Mono> proxy(ProxyExchange proxy) throws Exception { return proxy.uri(home.toString() + "/image/png").get(); } } ``` -------------------------------- ### GET /actuator/gateway/routefilters response Source: https://github.com/spring-cloud/spring-cloud-gateway/blob/main/docs/modules/ROOT/pages/spring-cloud-gateway-server-webflux/actuator-api.adoc Example JSON response from the routefilters endpoint, showing GatewayFilter factories with their string representations and null order values. ```json { "[AddRequestHeaderGatewayFilterFactory@570ed9c configClass = AbstractNameValueGatewayFilterFactory.NameValueConfig]": null, "[SecureHeadersGatewayFilterFactory@fceab5d configClass = Object]": null, "[SaveSessionGatewayFilterFactory@4449b273 configClass = Object]": null } ``` -------------------------------- ### Generate documentation site with Antora Source: https://github.com/spring-cloud/spring-cloud-gateway/blob/main/README.adoc Run this command from the project root to build the documentation site using the docs profile and Antora. It processes the README.adoc and copies it to the project root. ```bash ./mvnw -pl docs -P docs antora:antora ``` -------------------------------- ### application.yml - equivalent route definitions with shortcut notation Source: https://github.com/spring-cloud/spring-cloud-gateway/blob/main/docs/modules/ROOT/pages/spring-cloud-gateway-server-webflux/configuration.adoc Shows two equivalent route definitions in YAML: one using the named SetStatus filter with args, and one using the shortcut notation SetStatus=401. Both routes point to https://example.org. ```yaml spring: cloud: gateway: server: webflux: routes: - id: setstatus_route uri: https://example.org filters: - name: SetStatus args: status: 401 - id: setstatusshortcut_route uri: https://example.org filters: - SetStatus=401 ``` -------------------------------- ### MVC Proxy Exchange example: proxy request to /test Source: https://github.com/spring-cloud/spring-cloud-gateway/blob/main/docs/modules/ROOT/pages/spring-cloud-gateway-proxy-exchange.adoc Use this MVC controller to proxy a request to /test downstream to a remote server. Requires the spring-cloud-gateway-proxyexchange-webmvc module on the classpath. The ProxyExchange parameter is injected by Spring, and the uri() method sets the downstream URI before calling get(). ```java @RestController @SpringBootApplication public class GatewaySampleApplication { @Value("${remote.home}") private URI home; @GetMapping("/test") public ResponseEntity proxy(ProxyExchange proxy) throws Exception { return proxy.uri(home.toString() + "/image/png").get(); } } ``` -------------------------------- ### Build the project with Maven wrapper Source: https://github.com/spring-cloud/spring-cloud-gateway/blob/main/README.adoc Use this command to compile and test the Spring Cloud Gateway project. Requires JDK 17 and Maven (>=3.3.3) if using the mvn command instead. May need to increase Maven memory via MAVEN_OPTS. ```bash $ ./mvnw install ``` -------------------------------- ### Configure RewriteRequestParameter filter in YAML and Java Source: https://github.com/spring-cloud/spring-cloud-gateway/blob/main/docs/modules/ROOT/pages/spring-cloud-gateway-server-webmvc/filters/rewriterequestparameter.adoc Configure the RewriteRequestParameter filter in YAML or Java. The YAML route rewrites the 'campaign' parameter to 'fall2023' for requests to /products. The Java example uses addRequestParameter to set a parameter, but note it does not actually use RewriteRequestParameter; it demonstrates a similar filter setup. ```yaml spring: cloud: gateway: server: webmvc: routes: - id: rewriterequestparameter_route uri: https://example.org predicates: - Path=/products filters: - RewriteRequestParameter=campaign,fall2023 ``` ```java import static org.springframework.cloud.gateway.server.mvc.filter.BeforeFilterFunctions.addRequestParameter; import static org.springframework.cloud.gateway.server.mvc.filter.BeforeFilterFunctions.uri; import static org.springframework.cloud.gateway.server.mvc.handler.GatewayRouterFunctions.route; import static org.springframework.cloud.gateway.server.mvc.handler.HandlerFunctions.http; @Configuration class RouteConfiguration { @Bean public RouterFunction gatewayRouterFunctionsRewriteRequestParameter() { return route("rewriterequestparameter_route") .GET("products", http()) .before(uri("https://example.org")) .before(addRequestParameter("red", "blue")) .build(); } } ``` -------------------------------- ### Route CORS configuration with metadata cors Source: https://github.com/spring-cloud/spring-cloud-gateway/blob/main/docs/modules/ROOT/pages/spring-cloud-gateway-server-webflux/cors-configuration.adoc Configure CORS directly on a route using metadata with key 'cors'. The properties belong to Spring Framework CorsConfiguration. If no Path predicate is present, '/**' will be applied. This example allows all origins, GET and POST methods, all headers, and sets maxAge to 30 seconds. ```yaml spring: cloud: gateway: server: webflux: routes: - id: cors_route uri: https://example.org predicates: - Path=/service/** metadata: cors: allowedOrigins: '*' allowedMethods: - GET - POST allowedHeaders: '*' maxAge: 30 ``` -------------------------------- ### Global CORS configuration with allowedOrigins and allowedMethods Source: https://github.com/spring-cloud/spring-cloud-gateway/blob/main/docs/modules/ROOT/pages/spring-cloud-gateway-server-webflux/cors-configuration.adoc Configure global CORS behavior for the gateway. The map key is a URL pattern, and the value is a Spring Framework CorsConfiguration. This example allows requests from https://docs.spring.io for all GET paths. To also apply this configuration to requests not handled by a route predicate, set spring.cloud.gateway.server.webflux.globalcors.add-to-simple-url-handler-mapping to true. ```yaml spring: cloud: gateway: server: webflux: globalcors: cors-configurations: '[/**]': allowedOrigins: "https://docs.spring.io" allowedMethods: - GET ``` -------------------------------- ### Access route metadata from exchange Source: https://github.com/spring-cloud/spring-cloud-gateway/blob/main/docs/modules/ROOT/pages/spring-cloud-gateway-server-webflux/route-metadata-configuration.adoc Shows how to retrieve the Route object from an exchange and access its metadata properties. Use getMetadata() to get all properties or getMetadata(someKey) to get a single one. ```java Route route = exchange.getAttribute(GATEWAY_ROUTE_ATTR); // get all metadata properties route.getMetadata(); // get a single metadata property route.getMetadata(someKey); ``` -------------------------------- ### Create a Route Definition with POST /actuator/gateway/routes/{id} Source: https://github.com/spring-cloud/spring-cloud-gateway/blob/main/docs/modules/ROOT/pages/spring-cloud-gateway-server-webflux/actuator-api.adoc JSON body for creating a route via the actuator endpoint. Predicates and filters must be shortcut DSL strings. A successful creation returns 201 Created, and you must call POST /actuator/gateway/refresh to apply the change. ```json { "predicates": ["Path=/mypath/**", "Weight=mygroup,20"], "filters": ["StripPrefix=1"], "uri": "http://backend-service:8080", "order": 0 } ``` -------------------------------- ### Example errorMessage from RequestSize rejection Source: https://github.com/spring-cloud/spring-cloud-gateway/blob/main/docs/modules/ROOT/pages/spring-cloud-gateway-server-webflux/gatewayfilter-factories/requestsize-factory.adoc Example errorMessage header value returned when a request is rejected due to size. The response status is 413 Payload Too Large and the header contains the actual and permissible limits. ```plaintext errorMessage : Request size is larger than permissible limit. Request size is 6.0 MB where permissible limit is 5.0 MB ``` -------------------------------- ### GET /actuator/gateway/routes/{id} Source: https://github.com/spring-cloud/spring-cloud-gateway/blob/main/docs/modules/ROOT/pages/spring-cloud-gateway-server-webflux/actuator-api.adoc Displays information about a particular route. ```APIDOC ## [GET] /actuator/gateway/routes/{id} ### Description Displays information about a particular route. ### Method GET ### Endpoint /actuator/gateway/routes/{id} ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the route. ### Response #### Success Response (200 OK) No response body is specified. #### Response Example (No response body example provided) ``` -------------------------------- ### GET /actuator/gateway/routes Source: https://github.com/spring-cloud/spring-cloud-gateway/blob/main/docs/modules/ROOT/pages/spring-cloud-gateway-server-webflux/actuator-api.adoc Displays the list of routes defined in the gateway. ```APIDOC ## [GET] /actuator/gateway/routes ### Description Displays the list of routes defined in the gateway. ### Method GET ### Endpoint /actuator/gateway/routes ### Response #### Success Response (200 OK) No response body is specified. #### Response Example (No response body example provided) ``` -------------------------------- ### Generate proto descriptor with protoc Source: https://github.com/spring-cloud/spring-cloud-gateway/blob/main/docs/modules/ROOT/pages/spring-cloud-gateway-server-webflux/gatewayfilter-factories/jsontogrpc-factory.adoc Command to generate a proto descriptor file using protoc with the --descriptor_set_out flag. The proto file is located at src/main/resources/proto/hello.proto and the output is hello.pb. ```bash protoc --proto_path=src/main/resources/proto/ \ --descriptor_set_out=src/main/resources/proto/hello.pb \ src/main/resources/proto/hello.proto ``` -------------------------------- ### GET /actuator/gateway/globalfilters Source: https://github.com/spring-cloud/spring-cloud-gateway/blob/main/docs/modules/ROOT/pages/spring-cloud-gateway-server-webflux/actuator-api.adoc Displays the list of global filters applied to the routes. ```APIDOC ## [GET] /actuator/gateway/globalfilters ### Description Displays the list of global filters applied to the routes. ### Method GET ### Endpoint /actuator/gateway/globalfilters ### Response #### Success Response (200 OK) No response body is specified. #### Response Example (No response body example provided) ``` -------------------------------- ### Configure Before Request Predicate in Java Source: https://github.com/spring-cloud/spring-cloud-gateway/blob/main/docs/modules/ROOT/pages/spring-cloud-gateway-server-webmvc/gateway-request-predicates.adoc Configures the Before route predicate using the Java DSL in GatewaySampleApplication.java. ```java import java.time.ZonedDateTime; import static org.springframework.cloud.gateway.server.mvc.filter.BeforeFilterFunctions.uri; import static org.springframework.cloud.gateway.server.mvc.handler.GatewayRouterFunctions.route; import static org.springframework.cloud.gateway.server.mvc.handler.HandlerFunctions.http; import static org.springframework.cloud.gateway.server.mvc.predicate.GatewayRequestPredicates.before; @Configuration class RouteConfiguration { @Bean public RouterFunction gatewayRouterFunctionsBefore() { return route("before_route") .route(before(ZonedDateTime.parse("2017-01-20T17:42:47.789-07:00[America/Denver]")), http() .before(uri("https://example.org")) .build(); } } ``` -------------------------------- ### GET /actuator/gateway/routefilters Source: https://github.com/spring-cloud/spring-cloud-gateway/blob/main/docs/modules/ROOT/pages/spring-cloud-gateway-server-webflux/actuator-api.adoc Displays the list of GatewayFilter factories applied to a particular route. ```APIDOC ## [GET] /actuator/gateway/routefilters ### Description Displays the list of GatewayFilter factories applied to a particular route. ### Method GET ### Endpoint /actuator/gateway/routefilters ### Response #### Success Response (200 OK) No response body is specified. #### Response Example (No response body example provided) ``` -------------------------------- ### Configure Weight predicate in Java Source: https://github.com/spring-cloud/spring-cloud-gateway/blob/main/docs/modules/ROOT/pages/spring-cloud-gateway-server-webmvc/gateway-request-predicates.adoc Configuring weight-based routing using the Java DSL for GatewayRouterFunctions. ```java import static org.springframework.cloud.gateway.server.mvc.filter.BeforeFilterFunctions.uri; import static org.springframework.cloud.gateway.server.mvc.handler.GatewayRouterFunctions.route; import static org.springframework.cloud.gateway.server.mvc.handler.HandlerFunctions.http; import static org.springframework.cloud.gateway.server.mvc.predicate.GatewayRequestPredicates.path; import static org.springframework.cloud.gateway.server.mvc.predicate.GatewayRequestPredicates.weight; @Configuration class RouteConfiguration { @Bean public RouterFunction gatewayRouterFunctionsWeights() { return route("weight_high") .route(weight("group1", 8).and(path("/**")), http()) .before(uri("https://weighthigh.org")) .build().and( route("weight_low") .route(weight("group1", 2).and(path("/**")), http()) .before(uri("https://weightlow.org")) .build()); } } ``` -------------------------------- ### Spring Cloud Build tools directory structure Source: https://github.com/spring-cloud/spring-cloud-gateway/blob/main/README.adoc Shows the layout of the spring-cloud-build-tools directory, including checkstyle configuration and IntelliJ conventions files. ```text .spring-cloud-build-tools/ └── src ├── checkstyle │ └── checkstyle-suppressions.xml <3> └── main └── resources ├── checkstyle-header.txt <2> ├── checkstyle.xml <1> └── intellij ├── Intellij_Project_Defaults.xml <4> └── Intellij_Spring_Boot_Java_Conventions.xml <5> ``` -------------------------------- ### Bucket4j Caffeine dependencies Source: https://github.com/spring-cloud/spring-cloud-gateway/blob/main/docs/modules/ROOT/pages/spring-cloud-gateway-server-webflux/gatewayfilter-factories/requestratelimiter-factory.adoc Adds the Caffeine and Bucket4j Caffeine dependencies required for the Bucket4j RateLimiter example. ```xml com.github.ben-manes.caffeine caffeine ${caffeine.version} com.bucket4j bucket4j_jdk17-caffeine ${bucket4j.version} ``` -------------------------------- ### CacheRequestBody GatewayFilter Factory: Java and YAML configuration Source: https://github.com/spring-cloud/spring-cloud-gateway/blob/main/docs/modules/ROOT/pages/spring-cloud-gateway-server-webflux/gatewayfilter-factories/cacherequestbody-factory.adoc The Java example defines a RouteLocator bean that caches the request body for paths matching /downstream/** using the CacheRequestBody filter with a body class of String. The YAML example shows the equivalent configuration in application.yml, specifying the filter name and the bodyClass argument as java.lang.String. Both are required to set up the filter in Java and YAML configurations. ```java @Bean public RouteLocator routes(RouteLocatorBuilder builder) { return builder.routes() .route("cache_request_body_route", r -> r.path("/downstream/**") .filters(f -> f.prefixPath("/httpbin") .cacheRequestBody(String.class).uri(uri)) .build(); } ``` ```yaml spring: cloud: gateway: server: webflux: routes: - id: cache_request_body_route uri: lb://downstream predicates: - Path=/downstream/** filters: - name: CacheRequestBody args: bodyClass: java.lang.String ``` -------------------------------- ### Configure SetRequestHostHeader filter in Java Source: https://github.com/spring-cloud/spring-cloud-gateway/blob/main/docs/modules/ROOT/pages/spring-cloud-gateway-server-webmvc/filters/setrequesthostheader.adoc Java configuration using the BeforeFilterFunctions.setRequestHostHeader method. The filter replaces the host header with 'example.org'. ```java import static org.springframework.cloud.gateway.server.mvc.filter.BeforeFilterFunctions.uri; import static org.springframework.cloud.gateway.server.mvc.filter.BeforeFilterFunctions.setRequestHostHeader; import static org.springframework.cloud.gateway.server.mvc.handler.GatewayRouterFunctions.route; import static org.springframework.cloud.gateway.server.mvc.handler.HandlerFunctions.http; @Configuration class RouteConfiguration { @Bean public RouterFunction gatewayRouterFunctionsSetRequestHostHeader() { return route("set_request_host_header_route") .GET("/headers", http()) .before(uri("http://localhost:8080")) .before(setRequestHostHeader("example.org")) .build(); } } ``` -------------------------------- ### SampleRequestPredicates.java - headerExists predicate Source: https://github.com/spring-cloud/spring-cloud-gateway/blob/main/docs/modules/ROOT/pages/spring-cloud-gateway-server-webmvc/writing-custom-predicates-and-filters.adoc Example implementation of a custom RequestPredicate as a static method that checks for the presence of a named HTTP header. ```java import org.springframework.web.servlet.function.RequestPredicate; class SampleRequestPredicates { public static RequestPredicate headerExists(String header) { return request -> request.headers().asHttpHeaders().containsKey(header); } } ``` -------------------------------- ### GET /actuator/gateway/globalfilters Source: https://github.com/spring-cloud/spring-cloud-gateway/blob/main/docs/modules/ROOT/pages/spring-cloud-gateway-server-webflux/actuator-api.adoc Retrieves the global filters applied to all routes. The response is a map of filter class names to their order values. ```APIDOC ## GET /actuator/gateway/globalfilters ### Description Retrieves the global filters applied to all routes. The response is a map of filter class names to their order values. ### Method GET ### Endpoint /actuator/gateway/globalfilters ### Response #### Success Response (200) - **filter class name** (string) - The fully qualified class name of the global filter. - **order** (integer) - The order of the filter. #### Response Example { "org.springframework.cloud.gateway.filter.ReactiveLoadBalancerClientFilter@77856cc5": 10100, "org.springframework.cloud.gateway.filter.RouteToRequestUrlFilter@4f6fd101": 10000, "org.springframework.cloud.gateway.filter.NettyWriteResponseFilter@32d22650": -1, "org.springframework.cloud.gateway.filter.ForwardRoutingFilter@106459d9": 2147483647, "org.springframework.cloud.gateway.filter.NettyRoutingFilter@1fbd5e0": 2147483647, "org.springframework.cloud.gateway.filter.ForwardPathFilter@33a71d23": 0, "org.springframework.cloud.gateway.filter.AdaptCachedBodyGlobalFilter@135064ea": 2147483637, "org.springframework.cloud.gateway.filter.WebsocketRoutingFilter@23c05889": 2147483646 } ``` -------------------------------- ### Global filters response from /actuator/gateway/globalfilters Source: https://github.com/spring-cloud/spring-cloud-gateway/blob/main/docs/modules/ROOT/pages/spring-cloud-gateway-server-webflux/actuator-api.adoc Shows the JSON response from a GET request to `/actuator/gateway/globalfilters`, listing global filters and their order values. ```json { "org.springframework.cloud.gateway.filter.ReactiveLoadBalancerClientFilter@77856cc5": 10100, "org.springframework.cloud.gateway.filter.RouteToRequestUrlFilter@4f6fd101": 10000, "org.springframework.cloud.gateway.filter.NettyWriteResponseFilter@32d22650": -1, "org.springframework.cloud.gateway.filter.ForwardRoutingFilter@106459d9": 2147483647, "org.springframework.cloud.gateway.filter.NettyRoutingFilter@1fbd5e0": 2147483647, "org.springframework.cloud.gateway.filter.ForwardPathFilter@33a71d23": 0, "org.springframework.cloud.gateway.filter.AdaptCachedBodyGlobalFilter@135064ea": 2147483637, "org.springframework.cloud.gateway.filter.WebsocketRoutingFilter@23c05889": 2147483646 } ``` -------------------------------- ### Configure Route with RateLimiter Filter Source: https://github.com/spring-cloud/spring-cloud-gateway/blob/main/docs/modules/ROOT/pages/spring-cloud-gateway-server-webmvc/filters/ratelimiter.adoc Configures a route with rate limiting using the rateLimit filter. Sets capacity to 100 tokens per minute and uses the user principal name as the key resolver. ```java import static org.springframework.cloud.gateway.server.mvc.filter.BeforeFilterFunctions.uri; import static org.springframework.cloud.gateway.server.mvc.filter.Bucket4jFilterFunctions.rateLimit; import static org.springframework.cloud.gateway.server.mvc.handler.GatewayRouterFunctions.route; import static org.springframework.cloud.gateway.server.mvc.handler.HandlerFunctions.http; @Configuration class RouteConfiguration { @Bean public RouterFunction gatewayRouterFunctionsRateLimited() { return route("rate_limited_route") .GET("/api/**", http()) .before(uri("https://example.org")) .filter(rateLimit(c -> c.setCapacity(100) .setPeriod(Duration.ofMinutes(1)) .setKeyResolver(request -> request.servletRequest().getUserPrincipal().getName()))) .build(); } } ``` -------------------------------- ### Configure After Request Predicate in Java Source: https://github.com/spring-cloud/spring-cloud-gateway/blob/main/docs/modules/ROOT/pages/spring-cloud-gateway-server-webmvc/gateway-request-predicates.adoc Configures the After route predicate using the Java DSL in GatewaySampleApplication.java. ```java import java.time.ZonedDateTime; import static org.springframework.cloud.gateway.server.mvc.filter.BeforeFilterFunctions.uri; import static org.springframework.cloud.gateway.server.mvc.handler.GatewayRouterFunctions.route; import static org.springframework.cloud.gateway.server.mvc.handler.HandlerFunctions.http; import static org.springframework.cloud.gateway.server.mvc.predicate.GatewayRequestPredicates.after; @Configuration class RouteConfiguration { @Bean public RouterFunction gatewayRouterFunctionsAfter() { return route("after_route") .route(after(ZonedDateTime.parse("2017-01-20T17:42:47.789-07:00[America/Denver]")), http()) .before(uri("https://example.org")) .build(); } } ``` -------------------------------- ### POST /actuator/gateway/routes/{id_route_to_create} Source: https://github.com/spring-cloud/spring-cloud-gateway/blob/main/docs/modules/ROOT/pages/spring-cloud-gateway-server-webflux/actuator-api.adoc Creates a new route definition. The request body must use shortcut DSL strings for predicates and filters. Returns 201 Created on success. ```APIDOC ## [POST] /actuator/gateway/routes/{id_route_to_create} ### Description Creates a new route definition. The request body must use shortcut DSL strings for predicates and filters. Returns 201 Created on success. ### Method POST ### Endpoint /actuator/gateway/routes/{id_route_to_create} ### Parameters #### Path Parameters - **id_route_to_create** (string) - Required - The ID of the route to create. #### Request Body - **predicates** (array of strings) - Required - Predicates in shortcut DSL format (e.g., "Path=/foo/**"). - **filters** (array of strings) - Optional - Filters in shortcut DSL format (e.g., "StripPrefix=1"). - **uri** (string) - Required - The destination URI of the route. - **order** (number) - Optional - The route order. ### Request Example { "predicates": ["Path=/mypath/**", "Weight=mygroup,20"], "filters": ["StripPrefix=1"], "uri": "http://backend-service:8080", "order": 0 } ### Response #### Success Response (201 Created) No response body is specified. #### Response Example (No response body example provided) ``` -------------------------------- ### GET /uppercase/{param} Source: https://github.com/spring-cloud/spring-cloud-gateway/blob/main/docs/modules/ROOT/pages/spring-cloud-gateway-server-webmvc/java-routes-api.adoc Invokes the uppercase function by passing the input string as a path parameter. The response body contains the uppercased string. ```APIDOC ## GET /uppercase/{param} ### Description Invokes the `uppercase` function with the given path parameter and returns the uppercased string in the response body. ### Method GET ### Endpoint /uppercase/{param} ### Parameters #### Path Parameters - **param** (string) - Required - The input string to be uppercased. ### Response #### Success Response (200) - **body** (string) - The uppercased string. #### Response Example `HELLO` ``` -------------------------------- ### GET /actuator/gateway/routes/{id} Source: https://github.com/spring-cloud/spring-cloud-gateway/blob/main/docs/modules/ROOT/pages/spring-cloud-gateway-server-webflux/actuator-api.adoc Retrieves information about a single route by its ID. The response contains the route ID, predicate, filters, URI, and order. ```APIDOC ## [GET] /actuator/gateway/routes/{id} ### Description Retrieves information about a single route by its ID. The response contains the route ID, predicate, filters, URI, and order. ### Method GET ### Endpoint /actuator/gateway/routes/{id} ### Parameters #### Path Parameters - **id** (String) - Required - The route ID. For example, `first_route`. ### Response #### Success Response (200) - **route_id** (String) - The route ID. - **predicate** (String) - A human-readable string representation of the route predicates. - **filters** (Array) - The `GatewayFilter` factories applied to the route. - **uri** (String) - The destination URI of the route. - **order** (Number) - The route order. #### Response Example { "route_id": "first_route", "predicate": "(Paths: [/first], match trailing slash: true)", "filters": [], "uri": "https://www.uri-destination.org", "order": 0 } ``` -------------------------------- ### Enable HTTPS on the gateway server with server.ssl configuration Source: https://github.com/spring-cloud/spring-cloud-gateway/blob/main/docs/modules/ROOT/pages/spring-cloud-gateway-server-webflux/tls-and-ssl.adoc Configure the gateway to listen for HTTPS requests using Spring's standard server SSL settings. Requires a PKCS12 keystore on the classpath with the alias and password shown. ```yaml server: ssl: enabled: true key-alias: scg key-store-password: scg1234 key-store: classpath:scg-keystore.p12 key-store-type: PKCS12 ``` -------------------------------- ### Configure JsonToGrpc filter in Java Source: https://github.com/spring-cloud/spring-cloud-gateway/blob/main/docs/modules/ROOT/pages/spring-cloud-gateway-server-webflux/gatewayfilter-factories/jsontogrpc-factory.adoc Java configuration for a RouteLocator bean that applies the JsonToGrpc filter to the /json/hello path. The filter uses service 'HelloService', method 'hello', and protoDescriptor 'file:src/main/proto/hello.pb'. ```java @Bean public RouteLocator routes(RouteLocatorBuilder builder) { return builder.routes() .route("json-grpc", r -> r.path("/json/hello").filters(f -> { String service = "HelloService"; String method = "hello"; String protoDescriptor = "file:src/main/proto/hello.pb"; return f.jsonToGRPC(service, method, protoDescriptor); }).uri(uri)) } ``` -------------------------------- ### Configure StripPrefix GatewayFilter in application.yml Source: https://github.com/spring-cloud/spring-cloud-gateway/blob/main/docs/modules/ROOT/pages/spring-cloud-gateway-server-webflux/gatewayfilter-factories/stripprefix-factory.adoc This configuration strips two parts from the request path. For example, a request to /name/blue/red is forwarded to the downstream service as /red. ```yaml spring: cloud: gateway: server: webflux: routes: - id: nameRoot uri: https://nameservice predicates: - Path=/name/** filters: - StripPrefix=2 ``` -------------------------------- ### Logback configuration for separate access log file Source: https://github.com/spring-cloud/spring-cloud-gateway/blob/main/docs/modules/ROOT/pages/spring-cloud-gateway-server-webflux/reactor-netty-access-logs.adoc Logback configuration that creates a separate access log file using a FileAppender and an AsyncAppender, and sets the logger for `reactor.netty.http.server.AccessLog` to INFO with additivity false. ```xml access_log.log %msg%n ``` -------------------------------- ### Java Configuration for RemoteAddr with XForwardedRemoteAddressResolver Source: https://github.com/spring-cloud/spring-cloud-gateway/blob/main/docs/modules/ROOT/pages/spring-cloud-gateway-server-webflux/request-predicates-factories.adoc Shows how to configure routes in Java using XForwardedRemoteAddressResolver.maxTrustedIndex(1) and the remoteAddr predicate. ```java RemoteAddressResolver resolver = XForwardedRemoteAddressResolver .maxTrustedIndex(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") ) ``` -------------------------------- ### RemoveRequestHeader GatewayFilter factory example Source: https://github.com/spring-cloud/spring-cloud-gateway/blob/main/docs/modules/ROOT/pages/spring-cloud-gateway-server-webflux/gatewayfilter-factories/removerequestheader-factory.adoc Configures a route with a RemoveRequestHeader filter for the X-Request-Foo header. This filter removes the specified header before forwarding the request downstream. ```yaml spring: cloud: gateway: server: webflux: routes: - id: removerequestheader_route uri: https://example.org filters: - RemoveRequestHeader=X-Request-Foo ``` -------------------------------- ### Define default filters in application.yml Source: https://github.com/spring-cloud/spring-cloud-gateway/blob/main/docs/modules/ROOT/pages/spring-cloud-gateway-server-webflux/gatewayfilter-factories/default-filters.adoc Configures default filters for all routes using the `spring.cloud.gateway.default-filters` property. The example adds a response header and a prefix path. ```yaml spring: cloud: gateway: default-filters: - AddResponseHeader=X-Response-Default-Red, Default-Blue - PrefixPath=/httpbin ``` -------------------------------- ### Spring Cloud Function application example Source: https://github.com/spring-cloud/spring-cloud-gateway/blob/main/docs/modules/ROOT/pages/spring-cloud-gateway-server-webmvc/java-routes-api.adoc A Spring Boot application that uses Spring Cloud Function. The function bean names become the paths for routing. ```java @SpringBootApplication public class DemoFunctionGatewayApplication { public static void main(String[] args) { SpringApplication.run(DemoFunctionGatewayApplication.class, args); } ```