基于OpenID Connect及Token Relay实现Spring Cloud Gateway

目录
  • 前言
  • 实现
    • Keycloak
    • 网关
    • 依赖项
    • 代码
    • 配置
    • 测试
  • 资源服务器
    • 依赖项
    • 代码
    • 配置
    • 测试
  • 结论

前言

当与Spring Security 5.2+ 和 OpenID Provider(如KeyClope)结合使用时,可以快速为OAuth2资源服务器设置和保护Spring Cloud Gateway。

Spring Cloud Gateway旨在提供一种简单而有效的方式来路由到API,并为API提供跨领域的关注点,如:安全性、监控/指标和弹性。

我们认为这种组合是一种很有前途的基于标准的网关解决方案,具有理想的特性,例如对客户端隐藏令牌,同时将复杂性保持在最低限度。

我们基于WebFlux的网关帖子探讨了实现网关时的各种选择和注意事项,本文假设这些选择已经导致了上述问题。

实现

我们的示例模拟了一个旅游网站,作为网关实现,带有两个用于航班和酒店的资源服务器。我们使用Thymeleaf作为模板引擎,以使技术堆栈仅限于Java并基于Java。每个组件呈现整个网站的一部分,以在探索微前端时模拟域分离。

Keycloak

我们再一次选择使用keyclope作为身份提供者;尽管任何OpenID Provider都应该工作。配置包括创建领域、客户端和用户,以及使用这些详细信息配置网关。

网关

我们的网关在依赖关系、代码和配置方面非常简单。

依赖项

  • OpenID Provider的身份验证通过org.springframework.boot:spring-boot-starter-oauth2-client
  • 网关功能通过org.springframework.cloud:spring-cloud-starter-gateway
  • 将令牌中继到代理的资源服务器来自org.springframework.cloud:spring-cloud-security

代码

除了常见的@SpringBootApplication注释和一些web控制器endpoints之外,我们所需要的只是:

@Bean
public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http,
    ReactiveClientRegistrationRepository clientRegistrationRepository) {
  // Authenticate through configured OpenID Provider
  http.oauth2Login();

  // Also logout at the OpenID Connect provider
  http.logout(logout -> logout.logoutSuccessHandler(
    new OidcClientInitiatedServerLogoutSuccessHandler(clientRegistrationRepository)));

  // Require authentication for all requests
  http.authorizeExchange().anyExchange().authenticated();

  // Allow showing /home within a frame
  http.headers().frameOptions().mode(Mode.SAMEORIGIN);

  // Disable CSRF in the gateway to prevent conflicts with proxied service CSRF
  http.csrf().disable();
  return http.build();
}

配置

配置分为两部分;OpenID Provider的一部分。issuer uri属性引用RFC 8414 Authorization Server元数据端点公开的bij Keyclope。如果附加。您将看到用于通过openid配置身份验证的详细信息。请注意,我们还设置了user-name-attribute,以指示客户机使用指定的声明作为用户名。

spring:
  security:
    oauth2:
      client:
        provider:
          keycloak:
            issuer-uri: http://localhost:8090/auth/realms/spring-cloud-gateway-realm
            user-name-attribute: preferred_username
        registration:
          keycloak:
            client-id: spring-cloud-gateway-client
            client-secret: 016c6e1c-9cbe-4ad3-aee1-01ddbb370f32

网关配置的第二部分包括到代理的路由和服务,以及中继令牌的指令。

spring:
  cloud:
    gateway:
      default-filters:
      - TokenRelay
      routes:
      - id: flights-service
        uri: http://127.0.0.1:8081/flights
        predicates:
        - Path=/flights/**
      - id: hotels-service
        uri: http://127.0.0.1:8082/hotels
        predicates:
        - Path=/hotels/**

TokenRelay激活TokenRelayGatewayFilterFactory,将用户承载附加到下游代理请求。我们专门将路径前缀匹配到与服务器对齐的server.servlet.context-path

测试

OpenID connect客户端配置要求配置的提供程序URL在应用程序启动时可用。为了在测试中解决这个问题,我们使用WireMock记录了keyclope响应,并在测试运行时重播该响应。一旦启动了测试应用程序上下文,我们希望向网关发出经过身份验证的请求。为此,我们使用Spring Security 5.0中引入的新SecurityMockServerConfigurers#authentication(Authentication)Mutator。使用它,我们可以设置可能需要的任何属性;模拟网关通常为我们处理的内容。

资源服务器

我们的资源服务器只是名称不同;一个用于航班,另一个用于酒店。每个都包含一个显示用户名的最小web应用程序,以突出显示它已传递给服务器。

依赖项

我们添加了org.springframework.boot:spring-boot-starter-oauth2-resource-server到我们的资源服务器项目,它可传递地提供三个依赖项。

  • 根据配置的OpenID Provider进行的令牌验证通过org.springframework.security:spring-security-oauth2-resource-server
  • JSON Web标记使用org.springframework.security:spring-security-oauth2-jose
  • 自定义令牌处理需要org.springframework.security:spring-security-config

代码

我们的资源服务器需要更多的代码来定制令牌处理的各个方面。

首先,我们需要掌握安全的基本知识;确保令牌被正确解码和检查,并且每个请求都需要这些令牌。

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

  @Override
  protected void configure(HttpSecurity http) throws Exception {
    // Validate tokens through configured OpenID Provider
    http.oauth2ResourceServer().jwt().jwtAuthenticationConverter(jwtAuthenticationConverter());
    // Require authentication for all requests
    http.authorizeRequests().anyRequest().authenticated();
    // Allow showing pages within a frame
    http.headers().frameOptions().sameOrigin();
  }

  ...
}

其次,我们选择从keyclope令牌中的声明中提取权限。此步骤是可选的,并且将根据您配置的OpenID Provider和角色映射器而有所不同。

private JwtAuthenticationConverter jwtAuthenticationConverter() {
  JwtAuthenticationConverter converter = new JwtAuthenticationConverter();
  // Convert realm_access.roles claims to granted authorities, for use in access decisions
  converter.setJwtGrantedAuthoritiesConverter(new KeycloakRealmRoleConverter());
  return converter;
}
[...]
class KeycloakRealmRoleConverter implements Converter<Jwt, Collection<GrantedAuthority>> {
  @Override
  public Collection<GrantedAuthority> convert(Jwt jwt) {
    final Map<String, Object> realmAccess = (Map<String, Object>) jwt.getClaims().get("realm_access");
    return ((List<String>) realmAccess.get("roles")).stream()
      .map(roleName -> "ROLE_" + roleName)
      .map(SimpleGrantedAuthority::new)
      .collect(Collectors.toList());
  }
}

第三,我们再次提取preferred_name作为身份验证名称,以匹配我们的网关。

@Bean
public JwtDecoder jwtDecoderByIssuerUri(<a href="https://javakk.com/tag/oauth2" rel="external nofollow"  target="_blank" >OAuth2</a>ResourceServerProperties properties) {
  String issuerUri = properties.getJwt().getIssuerUri();
  NimbusJwtDecoder jwtDecoder = (NimbusJwtDecoder) JwtDecoders.fromIssuerLocation(issuerUri);
  // Use preferred_username from claims as authentication name, instead of UUID subject
  jwtDecoder.setClaimSetConverter(new UsernameSubClaimAdapter());
  return jwtDecoder;
}
[...]
class UsernameSubClaimAdapter implements Converter<Map<String, Object>, Map<String, Object>> {

  private final MappedJwtClaimSetConverter delegate = MappedJwtClaimSetConverter.withDefaults(Collections.emptyMap());

  @Override
  public Map<String, Object> convert(Map<String, Object> claims) {
    Map<String, Object> convertedClaims = this.delegate.convert(claims);
    String username = (String) convertedClaims.get("preferred_username");
    convertedClaims.put("sub", username);
    return convertedClaims;
  }

}

配置

在配置方面,我们又有两个不同的关注点。

首先,我们的目标是在不同的端口和上下文路径上启动服务,以符合网关代理配置。

server:
  port: 8082
  servlet:
    context-path: /hotels/

其次,我们使用与网关中相同的颁发者uri配置资源服务器,以确保令牌被正确解码和验证。

spring:
  security:
    oauth2:
      resourceserver:
        jwt:
          issuer-uri: http://localhost:8090/auth/realms/spring-cloud-gateway-realm

测试

酒店和航班服务在如何实施测试方面都采取了略有不同的方法。Flights服务将JwtDecoder bean交换为模拟。相反,酒店服务使用WireMock回放记录的keyclope响应,允许JwtDecoder正常引导。两者都使用Spring Security 5.2中引入的new jwt()RequestPostProcessor来轻松更改jwt特性。哪种风格最适合您,取决于您想要具体测试的JWT处理的彻底程度和方面。

结论

有了所有这些,我们就有了功能网关的基础。它将用户重定向到keydeport进行身份验证,同时对用户隐藏JSON Web令牌。对资源服务器的任何代理请求都使用适当的access_token来丰富,该token令牌经过验证并转换为JwtAuthenticationToken,以用于访问决策。

到此这篇关于基于OpenID Connect及Token Relay实现Spring Cloud Gateway的文章就介绍到这了,更多相关Spring Cloud Gateway内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

(0)

相关推荐

  • Spring Cloud Gateway整合sentinel 实现流控熔断的问题

    目录 一.什么是网关限流: 二.gateway 整合 sentinel 实现网关限流: 三.sentinel 网关流控规则的介绍: 3.1.网关流控规则: 3.2.API 分组管理: 四.sentinel 网关流控实现的原理: 五.网关限流了,服务就安全了吗? 六.自定义流控异常消息: 一.什么是网关限流: 在微服务架构中,网关层可以屏蔽外部服务直接对内部服务进行调用,对内部服务起到隔离保护的作用,网关限流,顾名思义,就是通过网关层对服务进行限流,从而达到保护后端服务的作用. Sentinel

  • springCloud gateWay 统一鉴权的实现代码

    目录 一,统一鉴权 1.1鉴权逻辑 1.2代码实现 一,统一鉴权 内置的过滤器已经可以完成大部分的功能,但是对于企业开发的一些业务功能处理,还是需要我们自己 编写过滤器来实现的,那么我们一起通过代码的形式自定义一个过滤器,去完成统一的权限校验. 1.1 鉴权逻辑 开发中的鉴权逻辑: 当客户端第一次请求服务时,服务端对用户进行信息认证(登录) 认证通过,将用户信息进行加密形成token,返回给客户端,作为登录凭证 以后每次请求,客户端都携带认证的token 服务端对token进行解密,判断是否有效

  • SpringCloud GateWay网关示例代码详解

    目录 一.网关基本概念 1.API网关介绍 2.Spring Cloud Gateway 3.Spring Cloud Gateway核心概念 一.网关基本概念 1.API网关介绍 API 网关出现的原因是微服务架构的出现,不同的微服务一般会有不同的网络地址,而外部客户端可能需要调用多个服务的接口才能完成一个业务需求,如果让客户端直接与各个微服务通信,会有以下的问题:(1)客户端会多次请求不同的微服务,增加了客户端的复杂性.(2)存在跨域请求,在一定场景下处理相对复杂.(3)认证复杂,每个服务都

  • SpringCloud Gateway之请求应答日志打印方式

    目录 Gateway请求应答日志打印 第一步 第二步 Gateway全局请求日志打印 把请求体的数据存入exchange 编写全局日志拦截器代码 在代码中配置全局拦截器 Gateway请求应答日志打印 请求应答日志时在日常开发调试问题的重要手段之一,那么如何基于Spring Cloud Gateway做呢,请看我上代码. 第一步 创建RecorderServerHttpRequestDecorator,缓存请求参数,解决body只能读一次问题. public class RecorderServ

  • SpringCloud中Gateway实现鉴权的方法

    目录 一.JWT 实现微服务鉴权 1 什么是微服务鉴权 2.代码实现 一.JWT 实现微服务鉴权 JWT一般用于实现单点登录.单点登录:如腾讯下的游戏有很多,包括lol,飞车等,在qq游戏对战平台上登录一次,然后这些不同的平台都可以直接登陆进去了,这就是单点登录的使用场景.JWT就是实现单点登录的一种技术,其他的还有oath2等. 1 什么是微服务鉴权 我们之前已经搭建过了网关,使用网关在网关系统中比较适合进行权限校验. 那么我们可以采用JWT的方式来实现鉴权校验. 2.代码实现 思路分析 1.

  • SpringCloud Gateway读取Request Body方式

    目录 Gateway读取RequestBody 分析ReadBodyPredicateFactory 配置ReadBodyPredicateFactory 编写自定义GatewayFilterFactory 完整的yml配置 Gateway自定义filter获取body的数据为空 首先创建一个全局过滤器把body中的数据缓存起来 在自定义的过滤器中尝试获取body中的数据 解析body的工具类 Gateway读取Request Body 我们使用SpringCloud Gateway做微服务网关

  • springcloud gateway网关服务启动报错的解决

    目录 gateway网关服务启动报错 集成gateway 报错 原因分析 gateway网关运行时报错问题(版本问题) 父级中的版本问题 原因:父项目中的jdk版本问题 解决方法 gateway网关服务启动报错 集成gateway springcloud网关集成gateway服务 <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter

  • 基于OpenID Connect及Token Relay实现Spring Cloud Gateway

    目录 前言 实现 Keycloak 网关 依赖项 代码 配置 测试 资源服务器 依赖项 代码 配置 测试 结论 前言 当与Spring Security 5.2+ 和 OpenID Provider(如KeyClope)结合使用时,可以快速为OAuth2资源服务器设置和保护Spring Cloud Gateway. Spring Cloud Gateway旨在提供一种简单而有效的方式来路由到API,并为API提供跨领域的关注点,如:安全性.监控/指标和弹性. 我们认为这种组合是一种很有前途的基于

  • Spring Cloud Gateway使用Token验证详解

    引入依赖 <dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-dependencies</artifactId> <version>${spring-cloud.version}</version> <ty

  • 详解Spring Cloud Gateway基于服务发现的默认路由规则

    1.Spring Gateway概述 1.1 什么是Spring Cloud Gateway Spring Cloud Gateway是Spring官方基于Spring 5.0,Spring Boot 2.0和Project Reactor等技术开发的网关,Spring Cloud Gateway旨在为微服务架构提供一种简单而有效的统一的API路由管理方式.Spring Cloud Gateway作为Spring Cloud生态系中的网关,目标是替代Netflix ZUUL,其不仅提供统一的路由

  • 基于Nacos实现Spring Cloud Gateway实现动态路由的方法

    简介 该文档主要介绍以Nacos为配置中心,实现Spring Cloud GateWay 实现动态路由的功能.Spring Cloud Gateway启动时候,就将路由配置和规则加载到内存里,无法做到不重启网关就可以动态的对应路由的配置和规则进行增加,修改和删除.通过nacos的配置下发的功能可以实现在不重启网关的情况下,实现动态路由. 集成 Spring Cloud GateWay集成 spring-cloud-starter-gateway:路由转发.请求过滤(权限校验.限流以及监控等) s

  • Spring Cloud Gateway入门解读

    Spring Cloud Gateway介绍 前段时间刚刚发布了Spring Boot 2正式版,Spring Cloud Gateway基于Spring Boot 2,是Spring Cloud的全新项目,该项目提供了一个构建在Spring 生态之上的API网关,包括:Spring 5,Spring Boot 2和Project Reactor. Spring Cloud Gateway旨在提供一种简单而有效的途径来发送API,并为他们提供横切关注点,例如:安全性,监控/指标和弹性.当前最新的

  • Spring Cloud GateWay 路由转发规则介绍详解

    Spring在因Netflix开源流产事件后,在不断的更换Netflix相关的组件,比如:Eureka.Zuul.Feign.Ribbon等,Zuul的替代产品就是SpringCloud Gateway,这是Spring团队研发的网关组件,可以实现限流.安全认证.支持长连接等新特性. Spring Cloud Gateway Spring Cloud Gateway是SpringCloud的全新子项目,该项目基于Spring5.x.SpringBoot2.x技术版本进行编写,意在提供简单方便.可

  • Spring Cloud Gateway 服务网关快速实现解析

    Spring Cloud Gateway 服务网关 API 主流网关有NGINX.ZUUL.Spring Cloud Gateway.Linkerd等:Spring Cloud Gateway构建于 Spring 5+,基于 Spring Boot 2.x 响应式的.非阻塞式的 API.同时,它支持 websockets,和 Spring 框架紧密集成,用来代替服务网关Zuul,开发体验相对来说十分不错. Spring Cloud Gateway 是 Spring Cloud 微服务平台的一个子

  • 详解Spring Cloud Gateway 数据库存储路由信息的扩展方案

    动态路由背景 ​ 无论你在使用Zuul还是Spring Cloud Gateway 的时候,官方文档提供的方案总是基于配置文件配置的方式 例如: # zuul 的配置形式 routes: pig-auth: path: /auth/** serviceId: pig-auth stripPrefix: true # gateway 的配置形式 routes: - id: pigx-auth uri: lb://pigx-auth predicates: - Path=/auth/** filte

  • 详解Spring Cloud Gateway 限流操作

    开发高并发系统时有三把利器用来保护系统:缓存.降级和限流. API网关作为所有请求的入口,请求量大,我们可以通过对并发访问的请求进行限速来保护系统的可用性. 常用的限流算法比如有令牌桶算法,漏桶算法,计数器算法等. 在Zuul中我们可以自己去实现限流的功能 (Zuul中如何限流在我的书 <Spring Cloud微服务-全栈技术与案例解析>  中有详细讲解) ,Spring Cloud Gateway的出现本身就是用来替代Zuul的. 要想替代那肯定得有强大的功能,除了性能上的优势之外,Spr

  • Spring Cloud Gateway全局异常处理的方法详解

    前言 Spring Cloud Gateway是Spring官方基于Spring 5.0,Spring Boot 2.0和Project Reactor等技术开发的网关,Spring Cloud Gateway旨在为微服务架构提供一种简单而有效的统一的API路由管理方式.Spring Cloud Gateway作为Spring Cloud生态系中的网关,目标是替代Netflix ZUUL,其不仅提供统一的路由方式,并且基于Filter链的方式提供了网关基本的功能,例如:安全,监控/埋点,和限流等

随机推荐