Account

Glossary / Content-Security-Policy (CSP)

What is Content-Security-Policy (CSP)

Content-Security-Policy (CSP) is an HTTP header that lists the sources a page may load scripts, styles, images, fonts and other resources from. The browser blocks anything that is not on the list. This makes CSP the main defense against XSS, where an attacker injects foreign code into your page.

Check your site

>

A policy is a set of directives. script-src covers scripts, style-src styles and img-src images, while default-src sets the fallback for most other resource types (a few directives, such as frame-ancestors and form-action, do not fall back to it). Each directive lists the allowed sources: 'self' (your own origin), specific hosts, or 'none'.

When the browser meets a resource that is not on the list, such as a script an attacker injected through a vulnerability, it refuses to run it. So even if the site has an XSS hole, the injected code does not execute, because its source is not allowed.

CSP is the most powerful security header and also the fiddliest. A policy that is too strict breaks your own scripts and analytics; one that is too loose, for example with 'unsafe-inline', protects almost nothing. The usual approach is to build the policy gradually, starting in Content-Security-Policy-Report-Only mode, which reports violations without blocking them.

Example

Content-Security-Policy: default-src 'self'; script-src 'self' https://apis.example.com; object-src 'none'

Common mistakes

Related terms