Spring Cloud Gateway主要用於以下角色之一:
- OAuth Client
- OAuth Resource Server
1 Spring Cloud Gateway as an OAuth 2.0 Client
在這種情況下,任何未經身份驗證的傳入請求都將啓動授權碼流程。網關獲取令牌後,將在向後端服務發送請求時使用它:
添加依賴
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-client</artifactId>
</dependency>
application.yml
server:
port: 8080
servlet:
context-path: /api
spring:
security:
oauth2:
client:
registration:
cjscustom:
client-id: client-1
client-secret: 123456789
client-authentication-method: client_secret_basic
authorization-grant-type: authorization_code
redirect-uri: http://127.0.0.1:8080/api/login/oauth2/code/cjscustom
scope: openid,profile
provider:
cjscustom:
authorization-uri: http://localhost:9000/oauth2/authorize
token-uri: http://localhost:9000/oauth2/token
jwk-set-uri: http://localhost:9000/oauth2/jwks
cloud:
gateway:
default-filters:
- TokenRelay=
routes:
- id: resource-server-1
uri: http://localhost:8082
predicates:
- Path=/resource-1/**
- id: resource-server-2
uri: http://localhost:8083
predicates:
- Path=/resource-2/**
logging:
level:
root: debug
2 Spring Cloud Gateway as an OAuth 2.0 Resource Server
在這裏,Gateway充當了網關守衛的角色,強制每個請求在發送到後端服務之前都有一個有效的訪問令牌。此外,它還可以根據關聯的作用域檢查令牌是否具有訪問給定資源的適當權限:
3 參考
https://www.baeldung.com/spring-cloud-gateway-oauth2