Thymeleaf 是否提供 X-Frame-Options 响应头的自动配置?如何启用?
解读
面试官抛出此题,表面问“模板引擎有没有帮你把点击劫持的响应头写好”,实则考察三点:
- 是否把“模板渲染”与“Web 安全”两个层级分清楚;
- 是否知道 Spring Boot 在国内 99% 的 Thymeleaf 项目里才是真正的“配置中枢”;
- 能否把“启用”动作落地到代码与配置,而不是背概念。
如果候选人回答“Thymeleaf 自带标签能写 X-Frame-Options”,直接判负;答“要加 Filter”但说不清 Spring Security 的 DSL,只能算半对;能把 Spring Security 的 frameOptions() 配置与 Thymeleaf 的片段复用、URL 重写结合起来谈,才是加分项。
知识点
- Thymeleaf 本身仅负责把模板变成字节流,不会也不应该插手 HTTP 响应头。
- 国内生产环境几乎清一色用 Spring Boot + Spring Security,因此“X-Frame-Options 谁来写”等价于“Spring Security 如何写”。
- Spring Security 5.x 提供两种写法:
- Java DSL:
http.headers().frameOptions().deny(); // 或 sameOrigin() - yml 配置:
spring: security: headers: frame: deny
- Java DSL:
- 若项目未引入 Spring Security,需手写 OncePerRequestFilter 并在 doFilterInternal 中设置 response.setHeader("X-Frame-Options", "DENY"),随后注册到 Spring Boot 的 FilterRegistrationBean,order 要早于 ThymeleafViewResolver。
- 如果业务必须允许同域 iframe(如可视化大屏嵌入),用 sameOrigin() 即可;若需更细粒度,可改用 Content-Security-Policy: frame-ancestors 'self',此时 X-Frame-Options 可关闭。
- Thymeleaf 的 th:replace 与 th:insert 虽然能复用头部片段,但片段里写
<meta http-equiv="X-Frame-Options" content="DENY">无效,因为 meta 标签不能替代响应头。
答案
Thymeleaf 本身不提供 X-Frame-Options 响应头的自动配置;它只负责渲染 HTML,不写 HTTP 头。
国内项目通常配合 Spring Security,启用方式如下:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.headers()
.frameOptions().deny() // 或 sameOrigin()
.and()
.authorizeRequests()
.anyRequest().permitAll();
}
}
若不使用 Spring Security,则自定义 Filter:
@Component
public class FrameOptionsFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest request,
HttpServletResponse response,
FilterChain chain) throws IOException, ServletException {
response.setHeader("X-Frame-Options", "DENY");
chain.doFilter(request, response);
}
}
并在 FilterRegistrationBean 中把 order 设为 -100,保证在 ThymeleafViewResolver 之前执行。
至此,X-Frame-Options 响应头即可对每次请求生效,与 Thymeleaf 渲染的页面完全解耦。
拓展思考
- 如果项目需要“部分页面允许嵌入 iframe”,可以把路径粒度拆细:在 Spring Security 的 configure 里用
requestMatchers("/public/embed/**").headers().frameOptions().sameOrigin(),其余路径保持 deny。 - 对 SEO 与政企合规要求高的场景,国内监管已开始检查 CSP 的 frame-ancestors 指令;可以逐步用
Content-Security-Policy: frame-ancestors 'self' https://trusted.gov.cn替代 X-Frame-Options,并在 Thymeleaf 公共片段里通过<meta http-equiv="Content-Security-Policy" th:content="${cspPolicy}">动态下发,实现模板与策略同步。 - 若前端团队坚持使用 Thymeleaf 的“自然模板”做纯静态原型,可把上述 Filter 做成 profile=dev 时关闭、profile=prod 时开启,既保证设计人员本地预览无限制,又确保线上环境默认安全。