如何禁用Spring Security的HTTPS重定向?Tomcat SSL配置场景
解决Spring Security在HTTPS非443端口自动重定向的问题
嘿,我之前刚好碰到过一模一样的场景!你的问题根源在于Spring Security默认启用了通道安全检查,它会自动将HTTP请求重定向到HTTPS,但你的Tomcat已经在8080端口配置了SSL(也就是说8080本身就是HTTPS端口),Spring Security可能因为这个端口不是标准的443,误判当前请求为HTTP,从而触发不必要的重定向。下面是几种靠谱的解决方法:
方法1:直接禁用通道安全检查(最简单)
如果你的应用全程都在HTTPS下运行,不需要Spring Security帮你做HTTP/HTTPS的跳转控制,直接关闭这个功能就可以了。在你的Spring Security配置类里添加如下代码:
import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { // 先配置你的登录拦截器、权限规则等内容 http .authorizeRequests() .antMatchers("/login").permitAll() .anyRequest().authenticated() .and() .formLogin() .loginPage("/login") // 其他登录相关配置... .and() // 关键:关闭通道安全检查,彻底禁用HTTPS重定向 .requiresChannel().disable(); } }
这个方法最直接,我当时就是这么解决的,亲测有效!
方法2:告诉Spring Security当前端口是安全的
如果你不想完全关闭通道安全,只是想让它识别8080端口为HTTPS端口,可以配置端口映射:
@EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http // 其他配置... .requiresChannel() .anyRequest().requiresSecure() // 要求所有请求都是安全的(HTTPS) .and() // 映射端口:告诉Spring Security 8080是HTTPS端口,不需要重定向到443 .portMapper() .http(8080).mapsTo(8080); } }
这样Spring Security就会认为8080端口的请求已经是HTTPS,不会再触发重定向了。
方法3:针对特定请求禁用重定向
如果只需要对登录相关的请求禁用重定向,其他请求保留通道安全检查,可以这样配置:
@EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/login", "/do-login").permitAll() .anyRequest().authenticated() .and() .formLogin() .loginPage("/login") .loginProcessingUrl("/do-login") .and() .requiresChannel() // 允许登录相关请求走当前端口(不强制重定向) .antMatchers("/login", "/do-login").requiresInsecure() // 其他请求仍然强制HTTPS .anyRequest().requiresSecure(); } }
补充说明
你Tomcat里的Connector配置是没问题的,已经正确开启了SSL:
<Connector port="8080" protocol="org.apache.coyote.http11.Http11NioProtocol" maxThreads="150" SSLEnabled="true" clientAuth="false" keystoreFile="conf/expchannel.pfx" keystorePass="***" keystoreType="PKCS12">
问题核心就是Spring Security的默认通道安全逻辑,只要按照上面的方法调整配置就能解决啦!
内容的提问来源于stack exchange,提问作者Gobanit
相关产品推荐
相关产品推荐

