gpt4 book ai didi

express - Express 中的内容安全策略报告空对象

转载 作者:行者123 更新时间:2023-12-03 08:33:53 28 4
gpt4 key购买 nike

我的 Web 应用程序在后端使用 Node.js 和 Express。当违反内容安全策略 (CSP) 时,报告 URI 报告空对象。我的后台代码如下:

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

app.use(helmet({
contentSecurityPolicy: {
directives: {
// some policies here
reportUri: ["/my_amazing_csp_report_parser"],
},
},
}));

app.use('/my_amazing_csp_report_parser', (req, res, next) => {
console.log(req.body);
next();
})

我在 Doc from MDN 上读到报告 URI 应报告整个 JSON 对象。但我的console.log(req.body);返回一个空对象。我想知道我的 JSON 对象解析是否错误 app.use(bodyParser.urlencoded({ extended: true }));app.use(bodyParser.json());

最佳答案

我不使用 React,所以我不会给你明确的代码。但我可以解释发生了什么。

CSP 报告与 <form method='POST'> 发送的数据不同。 <form> datas 具有内容类型“application/x-www-form-urlencoded”或“multipart/form-data”,用于发送 name/value 列表与服务器配对。这些数据可以是二进制(文件)或 urlencoded,因此您需要使用 bodyParser.urlencoded() .

CSP 报告以“application/json”MIME 类型发送,没有名称/值对,只有 body 。因此 bodyParser.urlencoded({ Extended: true }) 会给你空的主体,你需要使用类似 that 的东西:

app.use('/report-violation', bodyParser.json({ type: 'application/json' }));  # for old browsers
app.use('/report-violation', bodyParser.json({ type: 'application/reports+json' })); # for report-to directive
app.use('/report-violation', bodyParser.json({ type: 'application/csp-report' })); # for report-uri directive
app.use('/report-violation', (req, res) => {
// handle req.body
res.status(204).end()
});

* 我从来没有遇到过“application/csp-report”内容类型并且从未使用过它,这取决于你。至少不是IANA registered MIME type . 抱歉,这是来自 CSP 规范的报告的 MIME 类型。

不要忘记返回“204 No content”状态代码

Here是一些如何使用温斯顿记录器获取报告的示例,但我不知道它是否有效。

关于express - Express 中的内容安全策略报告空对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64436936/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com