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
相关产品推荐
相关产品推荐

