Spring Security 5.1.5中WhiteListedAllowFromStrategy配置失效求助
我之前也碰到过类似的配置问题,结合Spring Security 5.1.5的特性,给你几个具体的排查和解决方向:
1. 确认请求的Referer头是否符合要求
WhiteListedAllowFromStrategy的核心逻辑是通过请求的Referer头匹配白名单,如果请求里没有携带Referer,或者Referer不在你配置的白名单列表中,Spring Security就会默认返回X-Frame-Options: DENY。
你需要验证嵌入你页面的iframe所在页面(比如google.com的页面)是否发送了正确的Referer头。可以通过浏览器开发者工具的Network面板查看请求头,确认Referer是否为https://google.com。
2. 调整frameOptions的配置写法
你当前的配置先调用了.frameOptions().disable(),这会移除默认的X-Frame-Options头处理器,之后手动添加XFrameOptionsHeaderWriter可能存在优先级或注册不生效的问题。建议直接通过.strategy()方法指定白名单策略,不需要先disable:
@Override public void configure(HttpSecurity http) throws Exception { String permittedRoutes [] = {"/", "/register"}; http .headers() .frameOptions() .strategy(new WhiteListedAllowFromStrategy(Arrays.asList("https://google.com"))) .and() .and() .authorizeRequests() .antMatchers(permittedRoutes).permitAll() .antMatchers("/**").authenticated() .and() .formLogin() .loginPage("/") .defaultSuccessUrl("/home", true) .permitAll() .and() .logout() .logoutRequestMatcher(new AntPathRequestMatcher("/logout")) .permitAll() .invalidateHttpSession(true) .clearAuthentication(true) .deleteCookies("JSESSIONID") .logoutSuccessUrl("/?logout"); }
3. 注意WhiteListedAllowFromStrategy的局限性
在Spring Security 5.1.x中,WhiteListedAllowFromStrategy已经被标记为Deprecated,而且更重要的是,主流浏览器(比如Chrome、Firefox)已经逐步废弃了X-Frame-Options的ALLOW FROM指令,转而支持Content-Security-Policy的frame-ancestors规则。
如果你的业务场景允许,更推荐使用CSP来配置iframe允许的嵌入源,这样兼容性更好:
http.headers() .contentSecurityPolicy("frame-ancestors 'self' https://google.com;");
4. 排查是否有其他组件覆盖响应头
有时候应用服务器(比如Tomcat)或者其他自定义Filter可能会在Spring Security之后修改响应头,强制设置X-Frame-Options: DENY。你可以:
- 检查服务器的全局配置(比如Tomcat的
web.xml或context.xml)是否有相关头的设置; - 排查项目中是否有其他Filter拦截响应并修改了X-Frame-Options头。
5. 开启调试日志定位问题
开启Spring Security headers模块的DEBUG日志,能帮你清晰看到头处理器的执行逻辑:
在logback.xml或log4j2.xml中添加:
<logger name="org.springframework.security.web.headers" level="DEBUG"/>
通过日志可以查看请求的Referer是否被正确识别,以及策略是否匹配到白名单,从而定位为什么返回了DENY。
内容的提问来源于stack exchange,提问作者CodeWalker

