You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为带rewritePath的Spring GW路由添加tokenRelay实现认证

为Spring Gateway添加Token Relay过滤器(结合Keycloak授权码流)

1. 确保依赖齐全

如果使用Maven,需引入Spring Cloud Gateway和OAuth2 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>

2. 配置Spring Security认证规则

添加SecurityWebFilterChain Bean,实现OAuth2登录逻辑并保护业务API路径:

@Bean
public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
    http
        .authorizeExchange(exchanges -> exchanges
            .pathMatchers("/webapi/**").authenticated()
            .anyExchange().permitAll()
        )
        .oauth2Login(withDefaults())
        .csrf(csrf -> csrf.disable());

    return http.build();
}

3. 修改RouteLocator添加Token Relay过滤器

在现有路由的过滤器链中追加.tokenRelay(),该过滤器会将网关获取到的OAuth2令牌转发给后端资源服务:

@Bean
public RouteLocator customRouteLocator(RouteLocatorBuilder builder) {
    return builder.routes()
            .route("product-service", r -> r.path("/webapi/products/**")
                    .filters(f -> f.rewritePath("/webapi/(?<segment>.*)", "/api/v1/${segment}")
                            .tokenRelay())
                    .uri("lb://product-service"))
            .route("order-service", r -> r.path("/webapi/orders/**")
                    .filters(f -> f.rewritePath("/webapi/(?<segment>.*)", "/api/v1/${segment}")
                            .tokenRelay())
                    .uri("lb://order-service"))
            .build();
}

4. 配置Keycloak OAuth2客户端属性

在application.yml中填入你的Keycloak实例信息:

spring:
  security:
    oauth2:
      client:
        registration:
          keycloak:
            client-id: 你的客户端ID
            client-secret: 你的客户端密钥
            authorization-grant-type: authorization_code
            redirect-uri: "{baseUrl}/login/oauth2/code/keycloak"
            scope: openid, profile, email
        provider:
          keycloak:
            issuer-uri: https://你的Keycloak域名/auth/realms/你的Realm名称

补充说明

  • tokenRelay()依赖OAuth2 Client上下文,必须保证oauth2Login()配置正常,网关能完成授权码流获取令牌。
  • 后端资源服务需配置为OAuth2资源服务器,验证转发的令牌(可通过Spring Security OAuth2 Resource Server依赖,配置issuer-uri实现)。

内容的提问来源于stack exchange,提问作者Shay Zambrovski

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 08:23:21