Content Security Policy (CSP)

CSP Inline Scripts

When you enable CSP, it will block inline scripts, but there are some ways that you can allow inline scripts and still use Content Security Policy.

Inline Scripts are Blocked by Default with Content Security Policy

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:



<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”).

Allow Inline Scripts using a Nonce

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 'nonce-r@nd0m';

Assuming our nonce value is r@nd0m (you need to randomly generate a new nonce for every HTTP request), we can now use an inline script tag like this:

<script nonce="r@nd0m">

Allow Inline Scripts using a Hash

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 '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.

Other methods

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).

CSP Developer Field Guide

CSP Developer Field Guide

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 Copy

Struggling to stay on top of security advisories?

Advisory Week is a weekly roundup of all the security advisories published by the major software vendors.