Spring Boot在F5 BigIP SSL代理下重定向至HTTPS的配置问题
解决Spring Boot在F5代理下登录重定向为HTTP的问题
针对你遇到的问题,核心是让Spring Security识别到客户端发起的原始请求是HTTPS(通过F5传递的X-Forwarded-Proto头),从而生成正确的HTTPS重定向地址。以下是适配Spring Boot 1.2.8的具体解决方案:
1. 确保Tomcat正确信任代理头
你已经添加了application.properties的配置,但需要确保server.tomcat.internal-proxies包含F5 BigIP的IP地址(可以用正则匹配具体IP或IP段),这样Tomcat才会信任并处理X-Forwarded-Proto和X-Forwarded-For头。确认配置如下:
server.tomcat.remote-ip-header=x-forwarded-for server.tomcat.protocol-header=x-forwarded-proto server.tomcat.internal-proxies=192\.168\.1\.0/24|10\.0\.0\.0/8 # 替换为你的F5实际IP或IP段
2. 配置Spring Security使用转发的协议头
在你的FormLoginWebSecurityConfigurerAdapter中,添加ForwardedHeaderFilter让Spring Security识别原始请求协议,同时调整请求缓存配置,确保重定向时使用正确的协议:
@Configuration public static class FormLoginWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter { @Bean public FilterRegistrationBean forwardedHeaderFilter() { ForwardedHeaderFilter filter = new ForwardedHeaderFilter(); FilterRegistrationBean registrationBean = new FilterRegistrationBean(filter); registrationBean.setOrder(Ordered.HIGHEST_PRECEDENCE); return registrationBean; } @Override protected void configure(HttpSecurity http) throws Exception { http .csrf().disable() .authorizeRequests() .antMatchers("/error", "/js/**", "/css/**", "/img/**", "/help", "/favicon.ico").permitAll() .anyRequest().hasAuthority("USER") .and() .formLogin() .loginPage("/login") .failureUrl("/login-error") .permitAll() .and() .exceptionHandling().accessDeniedPage("/403") .and() .logout() .permitAll() .and() // 配置请求缓存,避免静态资源被缓存导致不必要重定向 .requestCache() .requestCache(new HttpSessionRequestCache() { @Override public void saveRequest(HttpServletRequest request, HttpServletResponse response) { if (new AntPathRequestMatcher("/login").matches(request) || new AntPathRequestMatcher("/login-error").matches(request) || new AntPathRequestMatcher("/403").matches(request)) { return; } super.saveRequest(request, response); } }); } }
3. 备选方案:手动配置端口映射
如果上述方法不生效,可以手动配置Spring Security的PortMapper和PortResolver,让它将HTTP的80端口映射到HTTPS的443端口:
@Override protected void configure(HttpSecurity http) throws Exception { PortMapperImpl portMapper = new PortMapperImpl(); portMapper.setPortMappings(Collections.singletonMap("80", "443")); PortResolverImpl portResolver = new PortResolverImpl(); portResolver.setPortMapper(portMapper); http .csrf().disable() .authorizeRequests() .antMatchers("/error", "/js/**", "/css/**", "/img/**", "/help", "/favicon.ico").permitAll() .anyRequest().hasAuthority("USER") .and() .formLogin() .loginPage("/login") .failureUrl("/login-error") .permitAll() .and() .exceptionHandling().accessDeniedPage("/403") .and() .logout() .permitAll() .and() .portMapper(portMapper) .portResolver(portResolver); }
验证方法
使用curl测试请求,查看重定向的Location头是否为HTTPS:
curl -v https://myapp.example.com
如果返回的Location是https://myapp.example.com/login,则配置生效。
内容的提问来源于stack exchange,提问作者Ana Monzon
相关产品推荐
相关产品推荐

