Security

What is Content Security Policy?

Content Security Policy (CSP) is an HTTP security header that controls which resources a browser is allowed to load for a given web page. CSP helps prevent cross-site scripting (XSS), clickjacking, and other code injection attacks by whitelisting trusted content sources.

How Does Content Security Policy (CSP) Work?

CSP works by sending an HTTP header (Content-Security-Policy) with the server response that specifies approved sources for different types of resources. Directives like script-src control where JavaScript can be loaded from, style-src controls stylesheets, img-src controls images, and connect-src controls API endpoints. For example, a CSP of "script-src 'self' https://cdn.example.com" only allows scripts from the same origin and the specified CDN, blocking all other script sources.

Implementing CSP is one of the most effective defenses against XSS attacks because even if an attacker finds an injection point, the browser will refuse to execute scripts from unauthorized sources. CSP can be deployed gradually using the Content-Security-Policy-Report-Only header to monitor violations without blocking content. Many hosting platforms and CDNs like Cloudflare provide interfaces for configuring CSP headers. A strict CSP requires careful inventory of all third-party resources your site uses, including analytics, fonts, and advertising scripts.

Related Terms