Spring Boot Security结合Kubernetes Ingress时重定向路径错误问题
问题:Spring Boot应用部署Kubernetes后重定向丢失Ingress前缀路径
刚接手一个Spring Boot项目,迁移到Kubernetes后遇到异常:外部访问时应用始终重定向至/login,完全忽略了Ingress配置的前缀路径。
环境配置
Ingress配置如下:
apiVersion: networking.k8s.io/v1 kind: Ingress metadata: name: health-app-core namespace: dev spec: ingressClassName: traefik rules: - http: paths: - backend: service: name: health-app-core port: number: 8080 path: /core/dev pathType: Prefix status: loadBalancer: ingress: - ip: <MY_IP>
访问测试情况
- 集群内部访问正常:在集群Pod内直接调用服务,请求
health-app-core.dev.svc.cluster.local:8080/login返回200,能正常加载登录页面。 - 外部访问异常:请求
http://<MY_IP>/core/dev/login时,会被302重定向至http://<MY_IP>/login,最终返回404错误。curl日志显示重定向的Location头缺失Ingress前缀/core/dev。
解决方案
1. 配置Spring Boot上下文路径
让应用内部所有路径都带上Ingress的前缀/core/dev,重定向时会自动包含该前缀。在application.yml中添加:
server: servlet: context-path: /core/dev
或application.properties格式:
server.servlet.context-path=/core/dev
2. 配置Forwarded Headers支持
Ingress代理(此处为Traefik)会向应用传递X-Forwarded-*系列请求头,Spring需要识别这些头来生成正确的外部访问URL和重定向地址。添加以下配置:
server: forward-headers-strategy: framework
如果是Spring Security项目,需在Security配置中启用Forwarded Header过滤器:
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.web.SecurityFilterChain; import org.springframework.web.filter.ForwardedHeaderFilter; @Configuration public class SecurityConfig { @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http // 保留原有Security规则配置 .addFilterBefore(forwardedHeaderFilter(), null); return http.build(); } @Bean public ForwardedHeaderFilter forwardedHeaderFilter() { return new ForwardedHeaderFilter(); } }
3. 验证Ingress路径配置
确保Ingress的pathType为Prefix,部分旧版本Traefik可能需要将路径调整为/core/dev/(带末尾斜杠),新版本Traefik的Prefix匹配通常兼容不带斜杠的配置。同时确认Ingress Controller已正确完成请求转发配置。
内容的提问来源于stack exchange,提问作者Mr.Sparkle
相关产品推荐
相关产品推荐

