A Content Security Policy (CSP) is a response header that tells the browser which sources a page may load resources from. Anything not on the list is blocked. Its main job is to limit cross-site scripting: a script an attacker manages to inject into the page does not run when the policy does not allow it.
How it works
The policy is a list of directives, each naming a kind of resource and the sources allowed for it:
Content-Security-Policy: default-src 'self'; script-src 'self' https://cdn.example.com; img-src 'self' data:; frame-ancestors 'none'
Here default-src 'self' allows resources from the page's own origin, script-src adds one outside host for scripts, and img-src also allows data: images. Once a policy restricts scripts, inline scripts and eval() are blocked unless the policy explicitly allows them, for example with a nonce or a hash for each inline script.
The frame-ancestors directive controls which sites may embed the page. It is the newer replacement for X-Frame-Options as a defense against clickjacking, and it only works in the header: browsers ignore it in a <meta> tag.
To try a policy without breaking anything, send it as Content-Security-Policy-Report-Only. The browser then reports what it would have blocked, in the console and to a reporting endpoint if you set one, but blocks nothing.
Why it matters
Cross-site scripting lets an attacker run code in your visitors' browsers as if it came from your site: reading what they type, acting as them, or sending them elsewhere. A CSP does not remove the bug that let the script in, but it stops the browser from running it. Of the security headers, it is also the one that takes the most care to set up.
What can go wrong
- A policy goes live untested and blocks the site's own inline scripts, a payment form or a chat widget.
- The policy allows
'unsafe-inline'or a broad wildcard to make the errors go away, and no longer stops injected scripts. - A new third-party script is added later and fails without anyone noticing, because nobody updated the policy.
- Two policies are sent, for example by the application and by a proxy, and the browser enforces both, so a resource has to pass each of them.
Check it
The Security headers checker shows whether a URL sends a Content-Security-Policy header. It gives a one-time reading, so it is worth running again after a deploy or a server change.
Start monitoring today
Websites go down and code throws errors. Ranetrace tells you when it happens to yours, why it matters and what to do next.