What is a Content Security Policy (CSP)?
Short answer
A Content Security Policy (CSP) is an HTTP header that lists which sources a page may load scripts, styles, images, and other content from. It is a strong defense against cross-site scripting, because the browser blocks anything not on the list.
An allowlist for content
Without a policy, a browser will run any script a page contains, including one injected by an attacker. CSP flips that to an allowlist: you declare the trusted sources, and the browser refuses everything else.
Content-Security-Policy: default-src 'self'; object-src 'none'; frame-ancestors 'none'Common directives
default-srcsets the fallback for other resource typesscript-srccontrols where JavaScript can load fromstyle-srccontrols stylesheetsimg-src,font-src,connect-srccontrol images, fonts, and fetch/XHRframe-ancestorscontrols who may embed your page in a frame
Source values
'self'allows the page's own origin'none'blocks everything for that directive- A domain like
https://cdn.example.comallows that host - A nonce or hash allows a specific inline script you trust
- Avoid
'unsafe-inline', which largely defeats the protection
Content-Security-Policy-Report-Only to see what a policy would block without breaking the site, then tighten and switch to enforcing.