Skip to content
本页目录

iframe 安全

此处所说的 iframe 安全问题分为 2 类:

  • 自己网站被三方作为 iframe 引用
  • 自己网站通过 iframe 引入三方网站,三方网站不可控,可能会运行一些恶意脚本

iframe 劫持

禁止自己网站被三方 iframe 引用

1. js 重定向方案

通过 window.topwindow.self 对象进行对比,如果 topself 不一致,则说明被三方嵌入,那么就让三方网站重定向到我的网站。

注意:此种方式可以被 H5sandbox 禁止而失效

JS
if (window.self !== window.top) {
  window.top.location = window.self.location;
}
if (window.self !== window.top) {
  window.top.location = window.self.location;
}

2. 服务端配置 X-Frame-Options

这是个服务端的配置

参数:

  • DENY:禁止被作为 iframe 引用,同源也不行
  • SAMEORIGIN:可以在同源中被作为 iframe 引用,所以正常使用这个项
  • ALLOW-FROM:设置允许的白名单

2.1 Nginx 配置

Nginx
add_header X-Frame-Options SAMEORIGIN;
add_header X-Frame-Options SAMEORIGIN;

设置域名白名单,域名逗号分隔

NGINX
add_header X-Frame-Options "ALLOW-FROM http://demo.com,https://demo2.com";
add_header X-Frame-Options "ALLOW-FROM http://demo.com,https://demo2.com";

2.2 Apache 配置

APACHE
Header always append X-Frame-Options SAMEORIGIN
Header always append X-Frame-Options SAMEORIGIN

禁止引入的三方网站操作自己的网站

html5iframe 新增加了一个 sandbox 属性,用于提高 iframe 的安全性。其可选值如下:

配置值作用
""应用以下所有的限制,即以下所有操作都被允许
allow-forms允许表单提交
allow-scripts允许脚本执行
allow-same-origin允许 iframe 被视为同源,即可操作父级 DOMcookie
allow-top-navigation允许当前 iframe 的引用网页通过 url 跳转链接或加载内容
allow-popups允许浏览器打开新窗口进行跳转