This version is still in development and is not considered stable yet. For the latest stable version, please use Spring Cloud Gateway 4.1.5!

TokenRelay Filter

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 Server MVC can forward the OAuth2 access token of the currently authenticated user oauth2Login() is used to authenticate the user.

RouteConfiguration.java
import static org.springframework.cloud.gateway.server.mvc.filter.TokenRelayFilterFunctions.tokenRelay;
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<ServerResponse> gatewayRouterFunctionsAddReqHeader() {
		return route("resource")
			.GET("/resource", http("http://localhost:9000"))
				.filter(tokenRelay())
				.build();
    }
}

or this

application.yaml
spring:
  cloud:
    gateway:
      mvc:
        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 Server MVC add the following dependencies

  • org.springframework.boot:spring-boot-starter-oauth2-client

How does it work? The currently authenticated user’s own access token (obtained during login) is used and the extracted access token is placed in a request header for the downstream requests.

The Token Relay filter will only work if the proper spring.security.oauth2.client.* properties are set which will trigger creation of a OAuth2AuthorizedClientManager bean.
The default implementation used by the Token Relay filter uses an in-memory data store. You will need to provide your own implementation OAuth2AuthorizedClientService if you need a more robust solution.