Loading pattern...

What is CSP (Content Security Policy)?

CSP (Content Security Policy) is an HTTP security header that tells browsers which scripts, styles, images, and other resources are allowed to load on your page. It prevents XSS attacks by blocking inline scripts and unauthorized third-party resources. If an attacker injects malicious JavaScript, CSP blocks it from executing.

When Should You Use This?

Add CSP to all web apps to prevent XSS attacks. Start with a strict policy (only allow your own domain), then add exceptions for trusted third parties (CDNs, analytics, payment providers). Use nonces or hashes for inline scripts. Test CSP in "report-only" mode first to catch issues before enforcing. Use tools like Google CSP Evaluator to validate your policy.

Common Mistakes to Avoid

  • Using unsafe-inline or unsafe-eval—defeats the purpose of CSP; use nonces or hashes instead
  • Not testing in report-only mode—strict CSP can break third-party scripts; monitor violations first
  • Allowing * for script-src—too permissive; whitelist specific domains or use nonces
  • Forgetting about legacy browsers—older browsers ignore CSP; still validate and sanitize input
  • Not monitoring CSP violations—set up report-uri to log blocked scripts and fix false positives

Real-World Examples

  • GitHub—uses strict CSP to block XSS in user-generated content (Markdown, comments)
  • Google—enforces CSP on Gmail to prevent malicious scripts in emails
  • Stripe—strict CSP to protect payment forms from XSS attacks
  • Cloudflare—provides CSP templates and auto-configuration for common use cases

Category

Cybersecurity

Tags

cspcontent-security-policyxss-preventionhttp-headersweb-security

Permalink