0

我已经使用 node-helmet 设置了我的项目 CSP,所以它看起来像这样:

// app.js

let nonce = require('./config/nonce')

app.use(
  helmet.contentSecurityPolicy({
    directives: {
      defaultSrc: ["'self'"],
      scriptSrc: ["'self'", nonce],
      // other stuff
    },
  })
);

// config/nonce.js 

const crypto = require('crypto');
let nonce = crypto.randomBytes(16).toString('base64');

module.exports = nonce;
// faqController.js

require("dotenv").config();
let nonce = require('../config/nonce')

exports.faq = function (req, res) { 
  res.render("faq", {
    nonce: nonce
  });
};

我可以在我的 HTML 中将 nonce 显示为文本,<%= nonce %>因此我知道该值被正确传递,但是当我尝试将该值传递给 script 标签上的 nonce 属性时,该值似乎没有通过。我只是收到一条错误消息,说该脚本违反了我的 CSP

编辑#2:

我现在在控制台中收到此错误:

The source list for Content Security Policy directive 'script-src' contains an invalid source: 'myValueFromCrypto'. It will be ignored

我看到很多人建议使用加密来处理 nonce ......为什么我的 CSP 忽略它?

编辑#3:

我更改let nonce = crypto.randomBytes(16).toString('base64');let nonce = crypto.randomBytes(16).toString('hex');which 使 CSP 接受该值..但我仍然无法将加密创建的值传递到我的脚本标记中的 nonce 属性中...发生了什么事!

我觉得问题一定来自scriptSrc: ["'self'", nonce]......我真的不知道!

4

1 回答 1

0

我通过将我的 csp 更改为此解决了这个问题: scriptSrc: ["'self'", `'nonce-${nonce}'`],,希望有一天这对某人有所帮助!

于 2021-01-28T00:12:32.437 回答