在OAuth 2.0模式下使用Spring Cloud Gateway

Spring Cloud Gateway主要用于以下角色之一:

  • OAuth Client
  • *OAuth Resource Server

1 Spring Cloud Gateway as an OAuth 2.0 Client

在这种情况下,任何未经身份验证的传入请求都将启动授权码流程。网关获取令牌后,将在向后端服务发送请求时使用它:

在OAuth 2.0模式下使用Spring Cloud Gateway

添加依赖

<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充当了网关守卫的角色,强制每个请求在发送到后端服务之前都有一个有效的访问令牌。此外,它还可以根据关联的作用域检查令牌是否具有访问给定资源的适当权限:

在OAuth 2.0模式下使用Spring Cloud Gateway

3 参考

https://www.baeldung.com/spring-cloud-gateway-oauth2

https://docs.spring.io/spring-cloud-gateway/docs/current/reference/html/#token-relay-gatewayfilter-factory

https://datatracker.ietf.org/doc/html/rfc6749

https://www.rfc-editor.org/rfc/rfc6749

Original: https://www.cnblogs.com/cjsblog/p/16093204.html
Author: 废物大师兄
Title: 在OAuth 2.0模式下使用Spring Cloud Gateway

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/613127/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球