diff --git a/docs/src/main/asciidoc/spring-cloud-gateway.adoc b/docs/src/main/asciidoc/spring-cloud-gateway.adoc index e36dc626..eff9bb7f 100644 --- a/docs/src/main/asciidoc/spring-cloud-gateway.adoc +++ b/docs/src/main/asciidoc/spring-cloud-gateway.adoc @@ -1630,6 +1630,69 @@ public RouteLocator routes(RouteLocatorBuilder builder) { ---- ==== +=== Token Relay `GatewayFilter` Factory + +A Token Relay is where an OAuth2 consumer acts as a Client and +forwards the incoming token to outgoing resource requests. The +consumer can be a pure Client (like an SSO application) or a Resource +Server. + +Spring Cloud Gateway can forward OAuth2 access tokens downstream to the services +it is proxying. To add this functionlity to gateway you need to add the +`TokenRelayGatewayFilterFactory` like this: + +.App.java +[source,java] +---- +@Autowired +private TokenRelayGatewayFilterFactory filterFactory; + +@Bean +public RouteLocator customRouteLocator(RouteLocatorBuilder builder) { + return builder.routes() + .route("resource", r -> r.path("/resource") + .filters(f -> f.filter(filterFactory.apply())) + .uri("http://localhost:9000")) + .build(); +} +---- + +or this + +.application.yaml +[source,yaml] +---- +spring: + cloud: + gateway: + routes: + - id: resource + uri: http://localhost:9000 + predicates: + - Path=/resource + filters: + - TokenRelay= +---- + +and it will (in addition to logging the user in and grabbing a token) +pass the authentication token downstream to the services (in this case +`/resource`). + +To enable this for Spring Cloud Gateway add the following dependencies + +- `org.springframework.cloud:spring-cloud-gateway-server-security` + +How does it work? The +{githubmaster}/src/main/java/org/springframework/cloud/gateway/security/TokenRelayGatewayFilterFactory.java[filter] +extracts an access token from the currently authenticated user, +and puts it in a request header for the downstream requests. + +For a full working sample see https://github.com/spring-cloud-samples/sample-gateway-oauth2login[this project]. + +NOTE: The default implementation of `ReactiveOAuth2AuthorizedClientService` used by `TokenRelayGatewayFilterFactory` +uses an in-memory data store. You will need to provide your own implementation `ReactiveOAuth2AuthorizedClientService` +if you need a more robust solution. + === Default Filters To add a filter and apply it to all routes, you can use `spring.cloud.gateway.default-filters`.