Skip to main content
security

CSP (Content Security Policy)

CSP is an HTTP header that restricts which resources (scripts, styles, images, frames) a page can load. CSP mitigates XSS by preventing execution of inline scripts and scripts from unauthorized origins. A strict CSP (script-src 'nonce-random') blocks injected JavaScript even if an attacker finds an injection point.

Definition

Content Security Policy defines a whitelist of allowed content sources via the Content-Security-Policy HTTP header. Each directive controls a resource type: script-src restricts JavaScript sources, style-src restricts CSS, img-src restricts images, connect-src restricts fetch/XHR/WebSocket targets, and frame-ancestors restricts which sites can embed yours (replacing X-Frame-Options). A strict CSP uses nonces (script-src 'nonce-abc123') – the server generates a random nonce per response and adds it to both the CSP header and each legitimate <script> tag. Injected scripts lack the nonce and are blocked. CSP violations are reported to a configured endpoint (report-uri or report-to) for monitoring without breaking the page (Content-Security-Policy-Report-Only). Start with report-only, monitor violations, fix legitimate sources, then enforce.

Examples

  • Content-Security-Policy: default-src 'self'; script-src 'nonce-abc123'; style-src 'self'
  • Content-Security-Policy-Report-Only: ... report-uri /csp-reports
  • frame-ancestors 'self' replaces X-Frame-Options for clickjacking prevention

Related Protocols

Related Terms