解决方案:
一、设置http请求头的X-Frame-Options:
X-Frame-Options可以设置三个值
1、DENY 如果页面包含在框架中,则阻止呈现页面
2、SAMEORIGIN 与上面相同,除非页面与顶级框架集所有者属于同一域
3、ALLOW-FROM uri 页面只能被制定的uri嵌入到iframe 或 frame中
node 做中间层配置
- 引入helmet 第三方node库 https://www.npmjs.com/package/helmet
引入方式: npm install helemt --save
// express
import helmet from 'helmet'
app.use(helmet())
// 直接使用 helmet 等同于使用一下
/*app.use(helmet.contentSecurityPolicy());
app.use(helmet.dnsPrefetchControl());
app.use(helmet.expectCt());
app.use(helmet.frameguard()); // 进行iframe 加载限制
app.use(helmet.hidePoweredBy());
app.use(helmet.hsts());
app.use(helmet.ieNoOpen());
app.use(helmet.noSniff());
app.use(helmet.permittedCrossDomainPolicies());
app.use(helmet.referrerPolicy());
app.use(helmet.xssFilter());*/
使用helmet.frameguard() 进行配置
frameguard通过设置X-Frame-Options头部来减少点击劫持攻击。 这个header被frame-ancestors Content Security Policy指令所取代,但在旧浏览器上仍然有用。
options.action 是一个字符串,指定使用哪个指令—DENY或SAMEORIGIN。 (这个中间件不支持遗留指令ALLOW-FROM) 默认为SAMEORIGIN。
// 设置 "X-Frame-Options: DENY"
app.use(
helmet.frameguard({
action: "deny",
})
);
// 设置 "X-Frame-Options: SAMEORIGIN"
app.use(
helmet.frameguard({
action: "sameorigin",
})
);
2.引入frameguard https://www.npmjs.com/package/frameguard
const frameguard = require("frameguard");
// 不允许任何框架加载:
app.use(frameguard({ action: "deny" }));
//仅仅允许同源加载:
app.use(frameguard({ action: "sameorigin" }));
app.use(frameguard()); // 默认设置 为 sameorigin
二、 使用js解决(注意可以兼用js)
top!=self && window.top.location.replace(self.location)