When you have a Content-Security-Policy
header defined, the browser will automatically block inline scripts (unless you implement one of the workarounds specified below), such as:
<script> doSomething(); </script>
Or
<div onclick="doSomething();">Click Me</div>
You might see something like this as a result:
content security policy: the page’s settings blocked the loading of a resource at inline (“script-src”).
Or you might see this:
content security policy: the page’s settings blocked the loading of a resource at inline (“default-src”).
One of the easiest ways to allow inline scripts when using CSP is to use a nonce. A nonce is just a random, single use string value that you add to your Content-Security-Policy
header, like so:
script-src js-cdn.example.com 'nonce-rAnd0m';
Assuming our nonce value is rAnd0m
(you need to randomly generate a new nonce for every HTTP request), we can now use an inline script tag like this:
<script nonce="rAnd0m"> doSomething(); </script>
A second approach to allow inline scripts is to use a hash, with this approach you compute the hash of your JavaScript code, and put the value in our CSP policy:
script-src js-cdn.example.com 'sha256-xzi4zkCjuC8lZcD2UmnqDG0vurmq12W/XKM5Vd0+MlQ='
Tip: your browser developer tools console might compute the hash for you and output it in the console when inline scripts are blocked by CSP.
The unsafe-inline
source list value can be used to allow inline scripts, but this also defeats much of the purpose of CSP.
CSP Level 3 (newest browsers) support a source list value: unsafe-hashes
which can be used to allow inline script in javascript event handlers (eg onclick
or onmouseover
, etc).
Want to learn the ins and outs CSP? Grab a copy of the CSP Developer Field Guide. It's a short and sweet guide to help developers get up to speed quickly.
Grab a CopyAdvisory Week is a weekly roundup of all the security advisories published by the major software vendors.