4

I'm working on a project where I have a content security policy enabled that only allows inline scripts with a nonce to be executed.

header("Content-Security-Policy: script-src 'nonce-".$nonce."';");

and so on the page my script tags have the nonce inserted in them as such:

<script nonce="<?php echo $nonce; ?>" src="/static/js/global.js"></script>

This works perfectly fine for the most part, but my site also loads the page using an ajax request and some of the pages that are loaded via ajax requests also have script tags in them as such.

<script nonce="<?php echo $nonce; //the same nonce as before ?>"></script>

The nonce is generated and stored on a session basis so each of the script tags in the ajax request should have the same nonce as the original page, but for some reason I get this error in the chrome console:

jquery.min.js:2

Refused to execute inline script because it violates the following Content Security Policy directive: "script-src 'nonce-YTQ4NTU4NzU1YTlkZGY5MmYzNDZlMTc0MDRhNGNiZTk='". Either the 'unsafe-inline' keyword, a hash ('sha256-88nUYsb1c+aRY8mvRZ5hGPAkvH3REgfxFMQa6iIP4GY='), or a nonce ('nonce-...') is required to enable inline execution.

How do I make it so that the script tags loaded via the ajax request also get executed.

1

1 Answer 1

1

I figured out the cause for anyone else who runs into this issue in the future. It has to do with the way script tags work, and how JQuery appends them. When using the .append() or .html() functions, JQuery will start by appending the script tag, but immediately after it does that, the browser will check the new script tag for the existence of the nonce. Since JQuery does not add the nonce as an attribute before appending the script tag, that new script tag now gets disabled by the browser for missing the nonce when it was created. The workaround was to make my own function to append the scripts that works like the following below:

//create a script tag node
let node = document.createElement("script"); 

//this is the element where the script will get appended
let vr = document.getElementById("change-region"); 

//insert your nonce here from wherever you retrieve it from
let nonce = "sd234r8hf8wresiu"; //insert your nonce here from wherever you get your nonce

//add the nonce to the new script node we made
node.setAttribute("nonce", nonce); 

//add the source of your script
node.setAttribute("src", "/source/of/script");

//append the node of the script element and it should be accepted by the browser this time
vr.appendChild(node);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.