A Content Security Policy (CSP) is a response header that tells the browser where a page may load scripts, styles, images and other resources from.
If an attacker manages to slip a script into your page, a good policy stops the browser from running it.
The problem it solves
The attack CSP is built for is cross-site scripting (XSS): an attacker gets their own JavaScript into your page, often through a comment box that shows input back without escaping it. The browser can't tell that script from yours, so it runs with the same access: it can read the page and send requests as the signed-in user.
A policy gives the browser a list of what is allowed. Anything not on the list is blocked, even when it sits inside your own HTML. Escaping output is still the first defence; CSP is the second.
What a policy looks like
The server sends it as a header on each page. It is split over lines here to read, but sent as one:
Content-Security-Policy:
default-src 'self';
script-src 'self' https://cdn.example.com;
img-src 'self' data:Each part is a directive covering one kind of resource:
default-src 'self'is the fallback for resource-loading directives without a more specific rule, so those resources may only come from your own origin. It does not cover every CSP directive, such asform-actionorframe-ancestors.script-srcallows scripts from your origin and one named CDN.
Wondering how this was made? How we make these