Updated 11 days ago | GitHub

Content Security Policy

A Content Security Policy (CSP) regulates loading external resources. It allows developers to set restrictions on loading JavaScript, CSS, and other resources.

It is a good practice to set a baseline policy of default-src 'self' (which allows only resources originating from the current origin to be loaded — “Only load your own content”), and then to allowlist any additional resources which should be allowed. Allowlisting can be done by resource type or origination location. (Note: CSP’s 'self' source expression is distinct from the browser’s Same-Origin Policy, which is a separate browser security model.)

CSP directives are sent to the browser in the response header. The response header can be configured in the application or as a default in the web server configuration.

Example:
CSP directives which whitelist current page, Google APIs, and a Facebook embedded iframe.

default-src 'self';
script-src 'self' https://apis.google.com;
frame-src https://facebook.com

Note: prefer the more specific frame-src (for <frame>/<iframe>) and worker-src (for web workers) directives over child-src. CSP Level 3 un-deprecated frame-src; child-src remains valid but is the broader, less specific option (MDN: CSP child-src).

It is also a good idea to add frame-ancestors 'none' (or a strict allow-list) to prevent your own pages from being embedded in another site’s iframe — this is the modern, CSP-based replacement for the X-Frame-Options response header and is the recommended clickjacking defense (OWASP Clickjacking Defense Cheat Sheet).

Content Security Policy website