Skip to main content

Content Security Policy (CSP)

Content Security Policy is a W3C standard delivered via an HTTP header that controls which sources a browser may load. It is a key defense-in-depth control against cross-site scripting, limiting the impact of any injection.

Best Practice: Content Security Policy (CSP)

Content Security Policy is a browser security standard from the W3C that lets a site declare which sources of content are trusted. Delivered through the Content-Security-Policy HTTP response header (or a meta tag), it restricts where scripts, styles, images, frames, and connections may come from. CSP is a primary defense-in-depth control against cross-site scripting (XSS) and data injection, because even if an attacker injects markup, the browser refuses to execute disallowed resources. It does not replace input sanitization but strongly limits the blast radius.

Step-by-Step Implementation Guidance

  1. Inventory all resource origins your site legitimately loads.
  2. Start in report-only mode with the Content-Security-Policy-Report-Only header to collect violations without breaking the site.
  3. Define a strict default-src and tighten per-directive (script-src, style-src, img-src, connect-src).
  4. Prefer nonces or hashes over unsafe-inline for scripts; avoid unsafe-eval.
  5. Add a reporting endpoint to monitor violations in production.
  6. Enforce the policy once reports are clean, and iterate as the site changes.

Common Mistakes Teams Make When Ignoring This Practice

  • Using a broad policy with unsafe-inline that negates XSS protection.
  • Allowing wildcard sources (*) that defeat the purpose.
  • Enforcing a strict policy without a report-only trial, breaking the site.
  • No reporting endpoint, so violations go unnoticed.
  • Forgetting to update the policy when adding new third-party scripts.

Tools and Techniques That Support This Practice

  • CSP Evaluator from Google for policy review.
  • report-uri and report-to directives with a collection service.
  • Nonce and hash generation in the build or server layer.
  • Security headers scanners such as Mozilla Observatory.

How This Practice Applies to Different Migration Types

  • Cloud Migration: Set CSP headers at the CDN or edge for consistent enforcement.
  • Database Migration: CSP limits damage from injection even as data layers change.
  • SaaS Migration: Re-scope source allowlists to the new vendor's domains.
  • Codebase Migration: Replace inline scripts with nonces when modernizing a legacy app.

Checklist

  • Resource origins inventoried.
  • Report-only mode trialed first.
  • Strict default-src and per-directive rules set.
  • Nonces or hashes instead of unsafe-inline.
  • Reporting endpoint configured.
  • Policy enforced and monitored.
  • Updated when new sources are added.