在OAuth 2.0模式下使用Spring Cloud Gateway
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