Spring Cloud Gateway

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Spring Cloud Gateway

 sofia     2022-06-28 我要评论

前言

当与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,以用于访问决策。

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们