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

Spring Boot Security开启preload后HSTS头未包含preload字段问题求助

Spring Security HSTS preload指令缺失问题解决

配置错误点修正

  1. 你当前代码中设置的maxAgeInSeconds(31536000)和预期的16000000数值不一致,先调整该参数
  2. Spring Security 5.4.6版本中,HSTS的preload指令默认不会自动追加,除了设置preload(true)外,你需要确保没有全局配置禁用了HSTS的完整属性输出

可用的两种解决方案

方案1:修正官方配置调用

如果要使用原生HSTS配置,调整代码如下:

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.headers(headers ->
        headers.httpStrictTransportSecurity(hstsConfig -> {
            hstsConfig.preload(true);
            hstsConfig.includeSubDomains(true);
            hstsConfig.maxAgeInSeconds(16000000);
            // 增加请求匹配器,确保所有HTTPS请求都触发完整HSTS头输出
            hstsConfig.requestMatcher(AnyRequestMatcher.INSTANCE);
        })
        .contentSecurityPolicy(contentSecurityPolicy ->
            contentSecurityPolicy
                .policyDirectives("script-src 'self'")
        )
        .addHeaderWriter(new StaticHeadersWriter("X-My-Custom-Header","myvalue"))
    );
    http.csrf().disable();
}

如果配置后preload仍未输出,属于5.4.x版本的已知小问题,直接使用方案2。

方案2:手动写入完整HSTS头(最稳妥)

该方案兼容性最好,不受Spring Security版本影响,优先推荐
直接禁用默认HSTS配置,用静态头写入器自定义完整值:

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.headers(headers ->
        // 禁用默认HSTS配置
        headers.httpStrictTransportSecurity().disable()
            .contentSecurityPolicy(contentSecurityPolicy ->
                contentSecurityPolicy
                    .policyDirectives("script-src 'self'")
            )
            // 手动写入完整的HSTS头
            .addHeaderWriter(new StaticHeadersWriter("Strict-Transport-Security","max-age=16000000; includeSubDomains; preload;"))
            .addHeaderWriter(new StaticHeadersWriter("X-My-Custom-Header","myvalue"))
    );
    http.csrf().disable();
}

验证注意事项

  • 必须使用HTTPS协议访问站点,HTTP请求下Spring Security默认不会返回HSTS响应头
  • 测试前先清除浏览器缓存/使用无痕模式,避免旧的HSTS策略缓存影响测试结果

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 12:18:02