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
相关产品推荐
相关产品推荐

