Content Security Policy tells the browser which origins may provide scripts, styles, images, fonts, frames and network connections. Its main value is to reduce what injected markup can execute or load.
Content Security Policy (CSP): reduce XSS risks and unwanted loads
Learn how to introduce a CSP progressively, understand its main directives, Report-Only mode, nonces and common mistakes.
Show contents
Begin with observation
A strict policy deployed in one step can break a real site. Inventory first-party and third-party resources, then use Content-Security-Policy-Report-Only to observe violations without blocking them. The CSP generator helps build a starting policy.
Understand the main directives
default-src provides a fallback. script-src and style-src deserve special attention because executable code and inline content are frequent sources of risk. img-src, font-src, connect-src, frame-src and object-src narrow other capabilities. Prefer explicit origins over broad wildcards.
Inline code, nonces and hashes
Allowing 'unsafe-inline' weakens an important CSP benefit. When inline code is unavoidable, nonces or CSP hashes can authorize specific blocks instead of all inline execution. A nonce must be unpredictable and generated for each response.
CSP complements application security
CSP does not sanitize untrusted HTML and does not repair broken authorization. Treat it as defense in depth. Combine it with secure coding, HTTPS and the security headers.
Roll out progressively
Start with reporting, remove unnecessary exceptions, test critical journeys, then enforce the policy. Revisit it when analytics, advertising, fonts or other third-party services change. Document every exceptional origin so the policy does not slowly become an unrestricted allow-list.
Was this article useful?
Sources and references
- W3C — Content Security Policy Level 3 (opens in a new tab)Page in English
- MDN — Content Security Policy (CSP) (opens in a new tab)Page in English
- OWASP — Content Security Policy Cheat Sheet (opens in a new tab)Page in English