What is Content Security Policy (CSP)?
Content Security Policy (CSP) is a security standard that helps prevent cross-site scripting (XSS), clickjacking, and other code injection attacks. By defining a whitelist of trusted sources for content, CSP headers instruct the browser to only execute or render resources from those sources, blocking malicious scripts.
Why CSP Matters for Web Security
XSS attacks remain one of the most common web vulnerabilities. Without CSP, an attacker can inject malicious scripts into your pages, stealing user data or defacing your site. CSP acts as an additional layer of defense, even if other security measures fail. It also helps mitigate data injection attacks by restricting where data can be loaded from.
How to Implement CSP Headers
1. Start with a Strict Policy
Begin with a restrictive policy that only allows resources from your own domain. For example:
default-src 'self';script-src 'self';style-src 'self';
This blocks all external scripts and styles, providing strong XSS prevention. However, it may break functionality that relies on third-party resources.
2. Add Exceptions for Trusted Sources
Identify the external resources your site needs (e.g., CDN libraries, analytics, or fonts). Add them to the appropriate directives:
script-src 'self' https://cdn.example.com;style-src 'self' https://fonts.googleapis.com;img-src 'self' data: https://*.google-analytics.com;
Use nonces or hashes for inline scripts to avoid using 'unsafe-inline'.
3. Use Nonces for Inline Scripts
A nonce is a random token generated per request. Add it to your CSP header and to the script tag:
script-src 'nonce-abc123';<script nonce='abc123'>...</script>
This allows specific inline scripts while blocking malicious ones.
Testing and Refining Your Policy
Use the Content-Security-Policy-Report-Only header to test a policy without enforcing it. Monitor reports for violations and adjust your policy accordingly. Gradually tighten the policy until it blocks attacks without breaking functionality.
Common Pitfalls to Avoid
- Using 'unsafe-inline' or 'unsafe-eval' – These weaken security. Use nonces or hashes instead.
- Overly permissive policies – Allowing too many sources reduces protection.
- Neglecting report-uri – Without reporting, you won't know about violations.
Conclusion
Implementing CSP headers is a critical step in securing your web application against XSS and data injection. By starting strict, adding exceptions carefully, and using nonces, you can achieve robust web security while maintaining site functionality. Regularly review and update your policy to adapt to new threats.