iis服务器助手广告
返回顶部
首页 > 资讯 > 精选 >基于OpenID Connect及Token Relay怎么实现Spring Cloud Gateway
  • 334
分享到

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

2023-07-02 12:07:51 334人浏览 安东尼
摘要

这篇文章主要介绍“基于OpenID Connect及Token Relay怎么实现spring Cloud Gateway”的相关知识,小编通过实际案例向大家展示操作过程,操作方法简单快捷,实用性强,

这篇文章主要介绍“基于OpenID Connect及Token Relay怎么实现spring Cloud Gateway”的相关知识,小编通过实际案例向大家展示操作过程,操作方法简单快捷,实用性强,希望这篇“基于OpenID Connect及Token Relay怎么实现Spring Cloud Gateway”文章能帮助大家解决问题。

前言

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

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

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

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

实现

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

Keycloak

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

网关

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

依赖项

  • OpenID Provider的身份验证通过org.springframework.boot:spring-boot-starter-oauth3-client

  • 网关功能通过org.springframework.cloud:spring-cloud-starter-gateway

  • 将令牌中继到代理的资源服务器来自org.springframework.cloud:spring-cloud-security

代码

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

@Beanpublic SecurityWebFilterChain springSecurityFilterChain(Serverhttpsecurity Http,    ReactiveClientReGIStrationRepository clientRegistrationRepository) {  // Authenticate through configured OpenID Provider  http.oauth3Login();  // 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:    oauth3:      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-oauth3-resource-server到我们的资源服务器项目,它可传递地提供三个依赖项。

  • 根据配置的OpenID Provider进行的令牌验证通过org.springframework.security:spring-security-oauth3-resource-server

  • JSON Web标记使用org.springframework.security:spring-security-oauth3-jose

  • 自定义令牌处理需要org.springframework.security:spring-security-config

代码

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

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

@Configuration@EnableWebSecuritypublic class SecurityConfig extends WebSecurityConfigurerAdapter {  @Override  protected void configure(HttpSecurity http) throws Exception {    // Validate tokens through configured OpenID Provider    http.oauth3ResourceServer().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作为身份验证名称,以匹配我们的网关。

@Beanpublic JwtDecoder jwtDecoderByIssuerUri(<a href="https://javakk.com/tag/oauth3" rel="external nofollow"  target="_blank" >OAuth3</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:    oauth3:      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处理的彻底程度和方面。

关于“基于OpenID Connect及Token Relay怎么实现Spring Cloud Gateway”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识,可以关注编程网精选频道,小编每天都会为大家更新不同的知识点。

--结束END--

本文标题: 基于OpenID Connect及Token Relay怎么实现Spring Cloud Gateway

本文链接: https://www.lsjlt.com/news/341669.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • 基于OpenID Connect及Token Relay实现Spring Cloud Gateway
    目录前言实现Keycloak网关依赖项代码配置测试资源服务器依赖项代码配置测试结论前言 当与Spring Security 5.2+ 和 OpenID Provi...
    99+
    2024-04-02
  • 基于OpenID Connect及Token Relay怎么实现Spring Cloud Gateway
    这篇文章主要介绍“基于OpenID Connect及Token Relay怎么实现Spring Cloud Gateway”的相关知识,小编通过实际案例向大家展示操作过程,操作方法简单快捷,实用性强,...
    99+
    2023-07-02
  • 基于kafka怎么实现Spring Cloud Bus消息总线
    这篇文章主要介绍“基于kafka怎么实现Spring Cloud Bus消息总线”的相关知识,小编通过实际案例向大家展示操作过程,操作方法简单快捷,实用性强,希望这篇“基于kafka怎么实现Spring Clo...
    99+
    2023-06-30
  • Spring Cloud gateway自定义错误处理Handler怎么实现
    本文小编为大家详细介绍“Spring Cloud gateway自定义错误处理Handler怎么实现”,内容详细,步骤清晰,细节处理妥当,希望这篇“Spring Cloud gateway自定义错误处...
    99+
    2023-07-05
  • Spring Cloud OAuth2怎么实现自定义token返回格式
    这篇“Spring Cloud OAuth2怎么实现自定义token返回格式”文章的知识点大部分人都不太理解,所以小编给大家总结了以下内容,内容详细,步骤清晰,具有一定的借鉴价值,希望大家阅读完这篇文章能有所收获,下面我...
    99+
    2023-07-02
  • 基于jQuery排序及怎么实现Tab栏特效
    今天小编给大家分享一下基于jQuery排序及怎么实现Tab栏特效的相关知识点,内容详细,逻辑清晰,相信大部分人都还太了解这方面的知识,所以分享这篇文章给大家参考一下,希望大家阅读完这篇文章后有所收获,下面我们一起来了解一下吧。一、jQuer...
    99+
    2023-06-29
  • Spring Security基于注解的接口角色访问控制怎么实现
    本文小编为大家详细介绍“Spring Security基于注解的接口角色访问控制怎么实现”,内容详细,步骤清晰,细节处理妥当,希望这篇“Spring Security基于注解的接口角色访问控制怎么实现”文章能帮助大家解决疑惑,下面跟着小编的...
    99+
    2023-06-16
  • vue基于el-table怎么实现多页多选及翻页回显
    这篇“vue基于el-table怎么实现多页多选及翻页回显”文章的知识点大部分人都不太理解,所以小编给大家总结了以下内容,内容详细,步骤清晰,具有一定的借鉴价值,希望大家阅读完这篇文章能有所收获,下面我们一起来看看这篇“vue基于el-ta...
    99+
    2023-07-04
  • 基于Java怎么用Mybatis实现oracle批量插入及分页查询
    这篇文章主要介绍“基于Java怎么用Mybatis实现oracle批量插入及分页查询”的相关知识,小编通过实际案例向大家展示操作过程,操作方法简单快捷,实用性强,希望这篇“基于Java怎么用Mybatis实现oracle批量插入及分页查询”...
    99+
    2023-07-02
  • 基于C++的摄像头图像采集及拼接程序该怎么实现
    今天给大家介绍一下基于C++的摄像头图像采集及拼接程序该怎么实现。文章的内容小编觉得不错,现在给大家分享一下,觉得有需要的朋友可以了解一下,希望对大家有所帮助,下面跟着小编的思路一起来阅读吧。程序的说明实现从摄像头实时采集单帧图像,之后完成...
    99+
    2023-06-28
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作