我已经使用 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]
......我真的不知道!