Content-Security-Policy builder
Choose the allowed sources and get a validated CSP header, with warnings for the settings that weaken it.
Sources: 'self', https://cdn.example.com, *.example.com, data:, 'nonce-abc123', 'sha256-…'. Separate with spaces.
Write a Content-Security-Policy without memorising the syntax
A Content-Security-Policy (CSP) is the most effective defence against cross-site scripting that a web application can add, and it is also one of the easiest headers to get wrong. The policy is a list of directives separated by semicolons, each with its own list of sources, and a single typo or a stray 'unsafe-inline' can quietly turn the protection off or break the whole site.
Fill in the sources for scripts, styles, images, connections, fonts, frames and media, choose whether to forbid plugins (object-src 'none'), restrict base-uri, set who may frame your pages (frame-ancestors) and where forms may post, and the builder writes the header and an equivalent <meta> tag. Sources are validated, and the tool warns about the settings that weaken a policy: 'unsafe-inline' and 'unsafe-eval' in scripts, bare wildcards and https: as a script source.
A sensible path
- Start from
default-src 'self', then add the CDNs, API hosts and image hosts you really use. - Replace inline scripts with files, or use nonces or hashes.
- Deploy as Report-Only with a report endpoint, watch the reports for a week, then enforce.
- Pair it with the security headers analyzer to check the other headers.
In Spring Security: http.headers(h -> h.contentSecurityPolicy(c -> c.policyDirectives("..."))). In nginx: add_header Content-Security-Policy "..." always;. The policy is built in your browser.
Frequently asked questions
What does a Content-Security-Policy do?
It tells the browser which sources of scripts, styles, images, frames and connections are allowed for a page. If an attacker injects a script tag from a disallowed host, or an inline script, the browser refuses to run it, which neutralises most cross-site scripting.
What is the difference between default-src and script-src?
default-src is the fallback for every resource type that has no directive of its own. script-src, style-src, img-src and so on override it for their type. A strict policy sets default-src 'self' and adds only the exceptions needed.
How do I allow inline scripts safely?
Use a nonce: generate a random value per response, send script-src 'nonce-RANDOM' and add nonce="RANDOM" to the script tags. Or allow a specific script with its hash, 'sha256-...'. Avoid 'unsafe-inline'.
How do I roll out a CSP without breaking the site?
Send it as Content-Security-Policy-Report-Only first and collect the violation reports. Fix or allow what is legitimate, then switch to the enforcing header.