salodore
salodore

Reputation: 35

What is the right procedure to set a nonce in the csp policy?

I am trying to set a nonce in the csp policy, but it is not working as expected.

The following code is what I am currently using for testing purposes:

server.js

  express.use(function(req, res, next) {
    res.set({
      "Content-Security-Policy":"script-src 'self' 'nonce-random1'"
    });
    return next();
  });

index.html

  <script nonce="random1" type="text/javascript" src="/script1.js"> 
  </script>

I am getting this error in the browser's console: Refused to execute inline event handler because it violates the following Content Security Policy directive: "script-src 'self' 'nonce-random1'...

I tried adding the source /script1.js as if it was a domain for testing purposes:

  express.use(function(req, res, next) {
    res.set({
      "Content-Security-Policy":"script-src 'self' /script1.js"
    });
    return next();
  });

Obviously it is not working and I get the same error.

I tried looking in the docs and the syntax should be correct. I tried looking at similar questions or articles related but I haven't found anything helpful.

I want to avoid using unsafe-inline. In the future I'll implement a one time hash as nonce for every request.

Someone knows why nonce is failing?

Upvotes: 1

Views: 3754

Answers (1)

granty
granty

Reputation: 8496

Refused to execute inline event handler

means that you have event handler buil-in tag like <div onclick='handler()'> or <body onload='some_javascript_here'> etc.
Your <script nonce='random1'>...</script> is executed, you can insert into it console.log('I am done') to ensure that.

Replace inline event handlers by addEventListener() or use jQuery for that if suitable.

"Content-Security-Policy":"script-src 'self' /script1.js"

is wrong, /script1.js relative URLs is not allowed in the directive.
Your first CSP "Content-Security-Policy":"script-src 'self' 'nonce-random1'" is correct.

Upvotes: 2

Related Questions