Back to all terms
Securityintermediate

Content Security Policy (CSP)

An HTTP response header that allows fine-grained control over which resources a browser is allowed to load and execute for a page.

Also known as: CSP, content security policy header, CSP directives

Description

Content Security Policy is a security standard implemented as an HTTP response header that provides a declarative mechanism for web applications to specify trusted sources of content. By defining a whitelist of approved content origins, CSP effectively mitigates cross-site scripting (XSS), clickjacking, and other code injection attacks by instructing the browser to only execute or render resources from those approved sources.

CSP operates through a set of directives, each controlling a specific resource type: script-src for JavaScript, style-src for CSS, img-src for images, connect-src for AJAX/WebSocket endpoints, font-src for fonts, frame-src for iframes, and others. The default-src directive serves as a fallback for any unspecified resource types. Directives can reference specific domains, use keywords like 'self', 'none', 'unsafe-inline', or employ nonce-based and hash-based approaches for inline content.

Deploying CSP requires careful planning to avoid breaking legitimate functionality. The recommended approach is to start with Content-Security-Policy-Report-Only to monitor violations without enforcing the policy, analyze reports to identify issues, and then progressively tighten the policy. Nonce-based policies (script-src 'nonce-{random}') are preferred over hash-based approaches for dynamic applications because they allow per-request authorization of inline scripts without the maintenance burden of updating hashes when content changes.

Prompt Snippet

Implement Content Security Policy headers with a strict policy: default-src 'self'; script-src 'self' 'nonce-{random}'; style-src 'self' 'unsafe-inline'; img-src 'self' data: https:; connect-src 'self' https://api.example.com; frame-ancestors 'none'; base-uri 'self'; form-action 'self'. Generate unique nonces per request using crypto.randomBytes(16).toString('base64') and inject them into both the CSP header and script tags. Deploy in report-only mode first via Content-Security-Policy-Report-Only, configure a /api/csp-report endpoint to collect violations, and tighten the policy iteratively before switching to enforcement mode.

Tags

cspsecurity-headersxss-mitigationbrowser-security