问题描述
我已经用 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
});
};
我可以使用 <%= nonce %>
在我的 HTML 中将 nonce 显示为文本,所以我知道该值被正确传递,但是当我尝试将值传递给我的脚本标签上的 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');
这使 CSP 接受该值..但我仍然无法将 crypto 创建的值传递到我的脚本标签中的 nonce 属性中......发生了什么!
我觉得问题一定来自scriptSrc: ["'self'",nonce]
...我真的不知道!
解决方法
我通过将我的 csp 更改为这个来解决这个问题:
scriptSrc: ["'self'",`'nonce-${nonce}'`],
,希望有一天这能帮助到某人!