Content-Security-Policy: default-src 'self'; script-src 'self' 'nonce-r4nd0m'; img-src 'self' https://cdn.example.com; frame-ancestors 'none'
A Content Security Policy (CSP) is a response header. It tells the browser which sources of content are allowed. If an attacker injects a script, the browser refuses to run it unless it matches the policy.
What the example policy does:
- Resources default to the same origin.
- Scripts must come from the same origin, or carry the matching nonce.
- Images may also come from one CDN.
- The page cannot be put in a frame.
A nonce is a random value the server generates for each response. Only scripts with that value may run.
CSP blocks inline scripts and eval unless you allow them. So strict policies use a nonce per response, or hashes of the allowed scripts. They avoid 'unsafe-inline'.
Rolling it out: start with Content-Security-Policy-Report-Only. It collects reports of violations without breaking the site.
CSP is defence in depth, meaning an extra layer of protection. It limits the damage of XSS, but it does not replace escaping output.
- CSP is an allowlist of content sources for each type of resource.
- CSP blocks inline scripts and
evalby default. - Use nonces or hashes instead of
'unsafe-inline'. - Roll CSP out with report-only mode first.
- CSP is defence in depth, not a replacement for escaping output.