Glossary / Content-Security-Policy (CSP)
Content-Security-Policy (CSP)
Content-Security-Policy (CSP) is an HTTP header that defines an allowlist of sources a page may load scripts, styles, images, fonts and other resources from. Anything not on the list is blocked by the browser. It is 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 controls scripts, style-src controls styles, img-src controls images, and default-src sets the fallback for everything else. Each directive lists allowed sources: 'self' (your own origin), specific hosts, or 'none'.
When the browser meets a resource that is not on the list, say a script an attacker injected through a vulnerability, it simply refuses to run it. So even if an XSS hole exists, the injected code never executes because its source is not allowed.
CSP is the most powerful and also the most fiddly security header. Too strict and it breaks your own scripts and analytics; too loose (for example with 'unsafe-inline') and it barely protects anything. The usual path 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
- Adding 'unsafe-inline' and 'unsafe-eval' to script-src just to make things work, which guts the XSS protection you set out to add.
- Enabling a strict policy straight in production without Report-Only first, then breaking your own scripts, styles and analytics.
- Confusing CSP with CORS. CSP says what your page may load; CORS says who may read your API's response. They are different mechanisms.
- Setting script-src but forgetting default-src or object-src, leaving other resource types wide open.
Related terms
Found problems?
Slow hosting, SSL trouble or frequent downtime? Move to TomisHost: fast hosting with free SSL, daily backups and free migration help.
TomisHost hosting