How to implement Content Security Policy headers

· Category: Cybersecurity

How to implement Content Security Policy headers

What Is CSP?

Content Security Policy (CSP) is a browser security standard that prevents cross-site scripting (XSS) and data injection by controlling which resources the browser is allowed to load. It is delivered via the Content-Security-Policy HTTP header.

Basic Policy

A strict policy might look like this:

Content-Security-Policy: default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:;

Key Directives

  • default-src: Fallback for unspecified resource types.
  • script-src: Controls JavaScript sources.
  • style-src: Controls CSS sources.
  • frame-ancestors: Prevents clickjacking by controlling framing.

Reporting

Enable report-only mode to test policies without breaking functionality:

Content-Security-Policy-Report-Only: default-src 'self'; report-uri /csp-report;

CSP complements but does not replace output encoding and input validation. For broader API security, see how to secure a REST API. For transport security, how to set up SSL/TLS certificates for a web server is a prerequisite.