Spring Cloud Gateway WebFlux Native配置Actuator独立端口报trustedProxies不能为空
问题根源
当Spring Cloud Gateway Reactive项目同时开启Actuator独立端口和Native/AOT编译时,Actuator的内嵌Web服务器会意外复用Gateway的ServerHttpSecurity配置逻辑,但你仅为主Gateway服务器配置了trustedProxies,Actuator的独立服务器未配置对应参数,导致构建时触发trustedProxies must not be empty校验异常。
解决方案
1. 为Actuator独立端口单独配置可信代理
直接在配置文件中给Actuator的服务器指定trusted-proxies和转发头策略,让它拥有独立的配置:
# application.properties management.server.port=9090 # 启用原生转发头处理 management.server.forward-headers-strategy=NATIVE # 根据实际环境配置可信代理,示例为允许所有 management.server.trusted-proxies=0.0.0.0/0,::/0
或YAML格式:
# application.yaml management: server: port: 9090 forward-headers-strategy: NATIVE trusted-proxies: - 0.0.0.0/0 - ::/0
2. 隔离Gateway与Actuator的安全配置
自定义Gateway的安全配置类,通过条件注解限制它仅作用于Gateway主服务器,避免Actuator的内嵌服务器加载该配置:
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; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; @Configuration @EnableWebFluxSecurity # 仅当Gateway启用时加载该配置 @ConditionalOnProperty(name = "spring.cloud.gateway.enabled", havingValue = "true") public class GatewaySecurityConfig { @Bean public SecurityWebFilterChain gatewaySecurityFilterChain(ServerHttpSecurity http) { http .csrf().disable() .authorizeExchange() .anyExchange().permitAll() .and() .forwardedHeaders() .trustedProxies("0.0.0.0/0", "::/0"); // Gateway主服务器的可信代理配置 return http.build(); } }
Actuator的安全配置会使用默认规则,不会触发trustedProxies校验。
3. 调整Actuator的转发头策略(适合内部环境)
如果部署环境不需要严格的可信代理校验,可将Actuator的转发头策略设为FRAMEWORK,绕过trustedProxies的强制校验:
management.server.forward-headers-strategy=FRAMEWORK
注意:该方案会降低转发头安全性,仅建议在内部可信环境使用。
验证
配置完成后,重新执行Native镜像构建命令(如./gradlew nativeCompile或mvn native:compile),确认trustedProxies must not be empty异常不再出现。
内容的提问来源于stack exchange,提问作者calamaricoder
相关产品推荐
相关产品推荐

