Content Security Policy (CSP) is a security mechanism delivered as an HTTP response header that tells the browser which sources of content are permitted to load on a page. By defining an allowlist of trusted content sources for scripts, stylesheets, images, fonts, frames, and other resource types, CSP provides a strong defense against cross-site scripting (XSS), clickjacking, and other code injection attacks.
How It Works
A CSP header consists of directives that control different resource types. The script-src directive specifies where JavaScript can be loaded from. The style-src directive controls stylesheet sources. The img-src directive governs image sources. The frame-ancestors directive determines which sites can embed the page in an iframe. The default-src directive sets the fallback policy for any resource type not explicitly defined.
A well-configured CSP might look like: Content-Security-Policy: default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; frame-ancestors 'none'. This policy allows resources only from the same origin, permits inline styles (often necessary for functionality), allows data URIs for images, and prevents the page from being embedded in any iframe.
The most security-critical directive is script-src. Avoiding 'unsafe-inline' and 'unsafe-eval' in this directive significantly reduces XSS risk because even if an attacker injects HTML into the page, the browser will refuse to execute inline scripts. Nonce-based CSP takes this further by requiring each script tag to include a unique, server-generated token that changes with every page load, making it extremely difficult for injected scripts to execute.
Why It Matters
CSP acts as a second line of defense against XSS. Even if an application contains an XSS vulnerability, a properly configured CSP can prevent the injected code from executing. Security assessments evaluate CSP headers for weaknesses such as overly permissive source lists, the presence of unsafe-inline or unsafe-eval, and directives that include domains hosting user-controllable content.
Need your application tested? Get in touch.