如何限制其他iframe加载自己的网站

解决方案:

一、设置http请求头的X-Frame-Options:

X-Frame-Options可以设置三个值
1、DENY 如果页面包含在框架中,则阻止呈现页面
2、SAMEORIGIN 与上面相同,除非页面与顶级框架集所有者属于同一域
3、ALLOW-FROM uri 页面只能被制定的uri嵌入到iframe 或 frame中

node 做中间层配置

  1. 引入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)
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值