I'm using jQuery version 3.1.1 and I'm trying to implement Content Security Policy (CSP) directives on my webpage.
I'm getting the following error:
Refused to execute inline script because it violates the following Content Security Policy directive: "script-src 'self' 'nonce-c20t41c7-73c6-4bf9-fde8-24a7b35t5f71'". Either the 'unsafe-inline' keyword, a hash ('sha256-KAcpKskREkEQf5B3mhDTonpPg34XnzaUC5IoBrOUrwY='), or a nonce ('nonce-...') is required to enable inline execution.
The error is produced on line 82 of the main jquery.js script file. The content of this line is:
doc.head.appendChild( script ).parentNode.removeChild( script );
Basically, it adds an inline script tag to the DOM, that violates the CSP.
I do not want to use 'unsafe-inline'. Is there another way to circumvent this error?
As you can see on the CSP violation, I'm using CSP level 2 (nonce), but it is ignored. Would it be possible (somehow) to inform jQuery to use this nonce when appending the script tag?
This is how the HTML looks like (using an Express.js template for nonce)
<script nonce="<%=nonce%>" type="text/javascript" src="jquery.js"></script>
Once the HTML is rendered, the nonce attribute on the script tag matches the CSP nonce directive sent by the server.
It does work with plain JavaScript:
<script nonce="<%=nonce%>" type="text/javascript">
var userEmail = "<%=user.user.email%>";
</script>
Without the nonce attribute, this script tag would violate the CSP directive.