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

Spring Security 6自动化测试中Header配置的新API替代方案

Spring Security 6.1+ 替换废弃Headers配置的方案

原来的链式配置方法在Spring Security 6.1后已被废弃,改用基于Customizer的Lambda风格API即可实现相同的XSS保护和内容安全策略配置,替换后的代码如下:

@TestConfiguration
public static class SecurityConfiguration {
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http.headers(headers -> headers
                .xssProtection(xss -> xss.enabled(true))
                .contentSecurityPolicy(csp -> csp.policyDirectives("default-src 'self'")));
        return http.build();
    }
}

关键替换说明:

  • 废弃的http.headers()改为http.headers(HeadersCustomizer),用Lambda表达式封装Headers的所有配置,无需再用and()拼接
  • xssProtection()替换为xssProtection(xss -> xss.enabled(true)),显式启用XSS保护(和原配置默认行为一致)
  • contentSecurityPolicy(String)替换为contentSecurityPolicy(csp -> csp.policyDirectives("default-src 'self'")),通过Lambda传入策略指令字符串

内容的提问来源于stack exchange,提问作者Boni García

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 02:20:08