gsh*_*hac 2 express content-security-policy
我的 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();
})
Run Code Online (Sandbox Code Playgroud)
我在MDN 的文档中读到,报告 URI 应报告整个 JSON 对象。但我的console.log(req.body);返回一个空对象。我想知道我用app.use(bodyParser.urlencoded({ extended: true }));and解析 JSON 对象是否错误app.use(bodyParser.json());?
我不使用 React,所以我不会给你明确的代码。但我可以解释发生了什么。
CSP 报告与发送的数据不同<form method='POST'>。数据<form>的内容类型为“application/x-www-form-urlencoded”或“multipart/form-data”,用于将名称/值对列表发送到服务器。这些数据可以是二进制(文件)或 urlencoded,因此您需要使用bodyParser.urlencoded().
CSP 报告以“application/json”MIME 类型发送,并且没有名称/值对,只有body. 因此 bodyParser.urlencoded({ Extended: true }) 会给你空的主体,你需要使用类似的东西:
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()
});
Run Code Online (Sandbox Code Playgroud)
* 我从来没有遇到过“application/csp-report”内容类型,也从未使用过它,这取决于你。至少它不是IANA 注册的 MIME 类型。抱歉,这是来自 CSP 规范的报告的 MIME 类型。
不要忘记返回“204 No content”状态代码
这是一些如何使用温斯顿记录器获取报告的示例,但我不知道它是否有效。
| 归档时间: |
|
| 查看次数: |
814 次 |
| 最近记录: |