Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
350 views
in Technique[技术] by (71.8m points)

node.js - Pass crypto.js value to script nonce

I've set my projects CSP up with node-helmet so it looks like this:

// 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
  });
};

I can display the nonce as text in my HTML with <%= nonce %> so I know the value is being passed correctly, but when I try to pass the value to my nonce attribute on the script tag, the value doesn't seem to come through. I just get an error saying the script violates my CSP

EDIT #2:

I'm now getting this error in my console:

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

I've seen many people recommend using crypto for nonce's... why is my CSP ignoring it?

EDIT #3:

I changed let nonce = crypto.randomBytes(16).toString('base64'); to let nonce = crypto.randomBytes(16).toString('hex'); which makes the CSP accept the value.. but I'm still not able to pass the value created by crypto into my nonce attribute in my script tag... whats going on!

I feel like the issue must be coming from scriptSrc: ["'self'", nonce]... I really have no idea!

question from:https://stackoverflow.com/questions/65926574/pass-crypto-js-value-to-script-nonce

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

i solved the issue by changing my csp to this: scriptSrc: ["'self'", `'nonce-${nonce}'`],, hopefully this helps somebody one day!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...