Content Security Policy: Preventing XSS and Data Injection
How Content Security Policy (CSP) headers protect your web application from cross-site scripting and other code injection attacks.
Continue your mission
How Content Security Policy (CSP) headers protect your web application from cross-site scripting and other code injection attacks.
Content Security Policy (CSP) is an HTTP response header that tells the browser which sources of content are trusted for a given web page. It is one of the most effective defenses against cross-site scripting (XSS) and data injection attacks.
When a browser receives a CSP header, it enforces the policy by blocking any content that does not come from an approved source. If an attacker manages to inject a script tag pointing to their malicious server, the browser will refuse to load it because that server is not in the CSP allowlist.
The CSP header contains directives that control different types of resources. Each directive specifies which sources are permitted for that resource type.
default-src sets the fallback policy for all resource types not explicitly covered by other directives. Starting with default-src 'none' and then adding specific permissions is the most secure approach.
script-src controls where JavaScript can be loaded from. This is the most critical directive for preventing XSS. Setting script-src 'self' allows scripts only from your own domain.
style-src controls CSS sources. img-src controls image sources. connect-src controls where XMLHttpRequest, Fetch, and WebSocket connections can go. font-src, media-src, frame-src, and object-src control their respective resource types.
Start with a restrictive policy and relax it as needed:
Content-Security-Policy: default-src 'none'; script-src 'self'; style-src 'self'; img-src 'self'; connect-src 'self'; font-src 'self'; frame-ancestors 'none'; base-uri 'self'; form-action 'self';
This policy allows only resources from your own origin, blocks all framing (preventing clickjacking), and restricts form submissions to your domain.
If you use third-party services, add their domains explicitly: script-src 'self' https://cdn.example.com. Avoid using wildcards like * as they undermine the protection.
Many XSS attacks inject inline JavaScript (code directly in the HTML rather than in an external file). CSP can block inline scripts by not including 'unsafe-inline' in the script-src directive.
However, many existing applications rely heavily on inline scripts. Two approaches address this without resorting to 'unsafe-inline':
Nonces are random values generated per request. The server includes the nonce in both the CSP header and on legitimate script tags: script-src 'nonce-abc123' and . Only scripts with the matching nonce execute. The nonce must be cryptographically random and change with every page load.
Hashes allow specific inline scripts by including their hash in the policy: script-src 'sha256-base64hash...'. This works for static inline scripts that do not change between page loads.
CSP offers two modes. Content-Security-Policy enforces the policy by blocking violations. Content-Security-Policy-Report-Only allows violations but sends reports to a specified endpoint, letting you test a policy before enforcing it.
Use the report-uri or report-to directive to receive JSON reports of policy violations. These reports tell you which resource was blocked, which directive was violated, and the page URL. This data is invaluable for tuning your policy.
Deploy CSP in report-only mode first. Monitor reports for a few weeks to identify legitimate resources that your policy blocks. Adjust the policy to allow those resources. Once reports show only expected or inconsequential violations, switch to enforcement mode.
CSP is not a silver bullet. It does not replace input validation, output encoding, or other XSS prevention measures. It is a defense-in-depth layer that catches XSS attempts your other controls miss.
CDA Theater missions that address topics covered in this article.
Cryptographic technique that encrypts data while preserving its original format and length, enabling protection without breaking legacy system compatibility.
Guide to HTTP/2 security covering binary framing, HPACK compression attacks, rapid reset vulnerability, stream multiplexing risks, and mitigation strategies.
Explanation of Certificate Transparency framework, covering log servers, Signed Certificate Timestamps, monitoring capabilities, and detection of fraudulent certificates.
Written by CDA Wiki Team
Found an issue? Help improve this article.