【发布时间】:2021-05-01 17:25:35
【问题描述】:
我已经使用 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 显示为文本,因此我知道该值被正确传递,但是当我尝试将值传递给 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');,这使得 CSP 接受该值..但我仍然无法将加密创建的值传递到我的脚本标签中的 nonce 属性中......这是怎么回事!
我觉得问题一定来自scriptSrc: ["'self'", nonce]...我真的不知道!
【问题讨论】:
-
您能告诉我们使用该 ejs 文件的路径中的
res.render()代码吗?请[编辑[您的问题。 -
@O.Jones 是的!该问题已被编辑
标签: node.js express security cryptojs helmet.js