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

Content Security Policy Report Empty Object in Express

我的网络应用程序在后端使用 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); returns 是一个空对象。我想知道我是否在用 app.use(bodyParser.urlencoded({ extended: true }));app.use(bodyParser.json()); 解析我的 JSON 对象时出错?

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

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

CSP 报告以 'application/json' MIME-type 发送,没有 name/value 对,只有 body。因此 bodyParser.urlencoded({ extended: true }) 会给你空的 body,你需要使用类似 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'Content-type也没用过,看你的了。至少它不是 IANA registered MIME type 它是 CSP 规范报告的 MIME 类型,抱歉。

不要忘记return“204 无内容”状态码

Here 是一些如何使用 winston logger 获取报告的示例,但我不知道它是否有效。