You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot中根据server.ssl.enabled条件重定向至HTTPS

解决方案

你可以通过读取server.ssl.enabled配置项,动态决定是否添加强制HTTPS的规则,具体实现如下:

方式一:通过@Value注入配置

先注入server.ssl.enabled的配置值(默认设为false,避免未配置时出错):

@Value("${server.ssl.enabled:false}")
private boolean sslEnabled;

然后修改SecurityFilterChain的构建逻辑,仅当SSL启用时添加强制HTTPS规则:

@Bean
SecurityFilterChain getSecurityFilterChain(HttpSecurity httpSecurity) throws Exception {
    if (sslEnabled) {
        httpSecurity.requiresChannel(crmr -> crmr.anyRequest().requiresSecure());
    }
    return httpSecurity.authorizeRequests(eir -> eir.anyRequest().permitAll())
            .csrf(AbstractHttpConfigurer::disable)
            .build();
}

方式二:通过Environment获取配置

也可以直接在Bean方法中注入Environment来读取配置,无需额外成员变量:

@Bean
SecurityFilterChain getSecurityFilterChain(HttpSecurity httpSecurity, Environment env) throws Exception {
    boolean sslEnabled = Boolean.parseBoolean(env.getProperty("server.ssl.enabled", "false"));
    if (sslEnabled) {
        httpSecurity.requiresChannel(crmr -> crmr.anyRequest().requiresSecure());
    }
    return httpSecurity.authorizeRequests(eir -> eir.anyRequest().permitAll())
            .csrf(AbstractHttpConfigurer::disable)
            .build();
}

逻辑说明

  • 当server.ssl.enabled=true时,保留原有的强制HTTPS重定向规则;
  • 当server.ssl.enabled=false时,跳过该规则,允许请求通过HTTP访问。

内容的提问来源于stack exchange,提问作者KirEvse

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 19:43:16