iframe 安全
此处所说的 iframe 安全问题分为 2 类:
- 自己网站被三方作为
iframe引用 - 自己网站通过
iframe引入三方网站,三方网站不可控,可能会运行一些恶意脚本
iframe 劫持
禁止自己网站被三方 iframe 引用
1. js 重定向方案
通过 window.top 与 window.self 对象进行对比,如果 top 与 self 不一致,则说明被三方嵌入,那么就让三方网站重定向到我的网站。
注意:此种方式可以被 H5 的 sandbox 禁止而失效
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 SAMEORIGINHeader always append X-Frame-Options SAMEORIGIN禁止引入的三方网站操作自己的网站
html5 对 iframe 新增加了一个 sandbox 属性,用于提高 iframe 的安全性。其可选值如下:
| 配置值 | 作用 |
|---|---|
"" | 应用以下所有的限制,即以下所有操作都被允许 |
allow-forms | 允许表单提交 |
allow-scripts | 允许脚本执行 |
allow-same-origin | 允许 iframe 被视为同源,即可操作父级 DOM 或 cookie 等 |
allow-top-navigation | 允许当前 iframe 的引用网页通过 url 跳转链接或加载内容 |
allow-popups | 允许浏览器打开新窗口进行跳转 |
前端知识点