如何在express.js node.js中设置X-Frame-Options

23

我有一些静态资源,希望在多个桌面/移动网络客户端的iframe中提供服务。

现在,如何白名单特定集合的来源,以允许设置X-Frame-Options头文件,从而可以嵌入不同桌面/移动网络客户端的资源, 并拒绝所有其他来源访问此资源。

通过一点挖掘,我开始使用 -

const app = express();

var allowCrossDomain = function (req, res, next) {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
    res.header('Access-Control-Allow-Headers', 'Content-Type, X-Requested-With, Authorization');
    if (req.method === "OPTIONS") res.send(200);
    else next();
}
app.use(allowCrossDomain);

现在,我该如何使用白名单中的来源值设置X-Frame-Options标头 -

3个回答

20

2
根据MDN的说法,在现代浏览器中,'x-Frame-Options'已经过时了,最好避免使用它:https://helmetjs.github.io/docs/frameguard/ (阅读“allow from”部分) - Ebrahim
1
我给它点了踩,因为导入整个库来完成如此微不足道的事情真是杀鸡焉用牛刀(尽管Express推荐这样做)。 - Steven

11

你所需要的就是helmet

npm install helmet --save 

const express = require('express')
const helmet = require('helmet')

const app = express()

app.use(helmet.frameguard())

2
如果我只添加app.use(helmet()),可以吗?我正在使用helmet版本3.21.3。 - Bijay Singh
1
@BijaySingh 是的,应该可以...根据文档 https://helmetjs.github.io/docs/ - Edwin O.

0
为了解决Steven的问题,您可以安装frameguard包only
   npm install helmet --save 

   const frameguard = require("frameguard");

   // Don't allow me to be in ANY frames:
   app.use(frameguard({ action: "deny" }));

   // Only let me be framed by people of the same origin:
    app.use(frameguard({ action: "sameorigin" }));
    app.use(frameguard()); // defaults to sameorigin

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接