SpringBoot基于Spring Security的HTTP跳转HTTPS
简单说说
之所以采用Spring Security来做这件事,一是Spring Security可以根据不同的URL来进行判断是否需要跳转(不推荐),
二是不需要新建一个TomcatServletWebServerFactory Bean,新建这个Bean可能会导致SpringBoot关于Server的配置失效。
三是网上大部分流传的通过实现WebServerFactoryCustomizer来自定义跳转,在我的项目中一直没能生效。
代码也很简单
package com.github.codeactions.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.web.SecurityFilterChain; /** * SecurityConfiguration * * @author hackyo * @since 2022/4/1 */ @Configuration @EnableWebSecurity @EnableMethodSecurity public class SecurityConfiguration { @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http.portMapper(portMapper -> portMapper.http(80).mapsTo(443)) .requiresChannel(requiresChannel -> requiresChannel.anyRequest().requiresSecure()); return http.build(); } }