Skip to content
uencoder

Content Security Policy

Content Security Policy (CSP) declares, via an HTTP header, a whitelist of sources a page may load resources from; it is the core mechanism for defending against XSS and content injection.

Purpose

To restrict resource loading sources through a whitelist, stopping injected malicious scripts from executing at the source.

Mechanism

The Content-Security-Policy header contains directives: default-src (default), script-src (scripts), style-src (styles), img-src (images), connect-src (fetch/XHR), etc. Values can be 'self', domains, nonces, or hashes. report-uri specifies violation reporting. Strict CSP uses nonce + strict-dynamic.

Use cases

  • XSS defense
  • Third-party script restriction
  • Inline script control
  • Violation monitoring

Examples

  • Input
    script-src 'self' 'nonce-abc123'
    Output
    Only same-origin + nonce scripts can execute

    Whitelist

Common errors

CSP includes unsafe-inline, weakening protection
Replace unsafe-inline with a nonce or hash

Related terms

References