TokenRelay
篩選器
Token Relay 是一種 OAuth2 消費者作為客戶端,並將傳入的令牌轉發到傳出的資源請求的方式。消費者可以是純粹的客戶端(例如 SSO 應用程式)或資源伺服器。
Spring Cloud Gateway Server MVC 可以轉發目前已驗證使用者的 OAuth2 存取令牌,當使用 oauth2Login()
驗證使用者時。
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();
}
}
或這個
application.yaml
spring:
cloud:
gateway:
mvc:
routes:
- id: resource
uri: http://localhost:9000
predicates:
- Path=/resource
filters:
- TokenRelay=
它將(除了讓使用者登入並獲取令牌之外)將驗證令牌向下傳遞到服務(在本例中為 /resource
)。
若要為 Spring Cloud Gateway Server MVC 啟用此功能,請新增以下依賴項
-
org.springframework.boot:spring-boot-starter-oauth2-client
它是如何運作的?目前已驗證使用者自己的存取令牌(在登入期間取得)會被使用,並且提取的存取令牌會放置在下游請求的請求標頭中。
Token Relay 篩選器僅在設定正確的 spring.security.oauth2.client.* 屬性時才會運作,這將觸發 OAuth2AuthorizedClientManager Bean 的建立。 |
Token Relay 篩選器使用的預設實作使用記憶體內資料儲存。如果您需要更穩健的解決方案,則需要提供您自己的實作 OAuth2AuthorizedClientService 。 |