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

Spring Boot3下Spring Cloud Gateway路径排除及Security放行配置方法

解决方案:Spring Cloud Gateway 路径排除与Spring Security放行配置

一、配置Gateway路由,让/gateway/manage/**由自身Controller处理

Spring Cloud Gateway的路由是按顺序匹配的,我们可以通过添加优先级更高的本地转发路由,拦截/gateway/manage/**请求,避免其被转发到外部服务。

修改后的spring.cloud.gateway.routes配置如下:

spring:
  cloud:
    gateway:
      routes:
        # 新增本地路由:匹配/gateway/manage/**,转发到网关自身处理
        - id: gateway-manage-local
          uri: forward:///
          predicates:
            - Path=/gateway/manage/**
        # 原有转发路由:仅处理非manage前缀的/gateway/**请求
        - id: forward-route2
          uri: https://my-domain.net
          predicates:
            - Path=/gateway/**
            - Path=!/gateway/manage/**
          filters:
            - TokenRelay
            - RewritePath=/gateway/(?<remaining>.*), /${remaining}
  • 新增的gateway-manage-local路由排在前面,会优先匹配所有/gateway/manage/**请求,通过forward:///将请求转发到网关自身的Controller,你只需在网关项目中编写对应路径的Controller即可。
  • 原有路由添加Path=!/gateway/manage/**作为双重校验,确保不会误匹配manage前缀的请求。

二、配置Spring Security放行/gateway/manage/**路径

Spring Boot3基于WebFlux构建Gateway,需通过WebFlux安全规则配置放行指定路径,以下提供两种实现方式:

方式1:Java配置类(推荐)

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity;
import org.springframework.security.config.web.server.ServerHttpSecurity;
import org.springframework.security.web.server.SecurityWebFilterChain;

@Configuration
@EnableWebFluxSecurity
public class GatewaySecurityConfig {

    @Bean
    public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
        http
            .authorizeExchange(exchanges -> exchanges
                // 放行/gateway/manage/**路径,允许匿名访问
                .pathMatchers("/gateway/manage/**").permitAll()
                // 其他所有路径需要OAuth2认证
                .anyExchange().authenticated()
            )
            // 保留原有OAuth2登录与客户端配置
            .oauth2Login()
            .and()
            .oauth2Client();
        return http.build();
    }
}

方式2:application.yml配置

spring:
  security:
    oauth2:
      client:
        registration:
          # 你的OAuth2客户端注册配置
        provider:
          # 你的OAuth2服务提供商配置
    webflux:
      authorize-exchange:
        mappings:
          - pattern: "/gateway/manage/**"
            access: "permitAll"
          - pattern: "/**"
            access: "authenticated"
  • permitAll表示该路径允许所有用户(包括匿名)访问,无需经过OAuth2认证流程。
  • 配置时需保留原有OAuth2的客户端和提供商配置,确保其他路径的认证逻辑不受影响。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 05:36:19