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();
    }

}
复制代码

 

posted @   hackyo  阅读(191)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· 没有源码,如何修改代码逻辑?
· PowerShell开发游戏 · 打蜜蜂
· 在鹅厂做java开发是什么体验
· WPF到Web的无缝过渡:英雄联盟客户端的OpenSilver迁移实战
历史上的今天:
2020-07-24 使用Docker单机部署Ceph
点击右上角即可分享
微信分享提示
主题色彩