ConfigGenerator

How to Create a Strong Content Security Policy (CSP) Header

Learn how to configure strict CSP headers to protect against XSS and injection attacks.

Content Security Policy (CSP) is an added layer of security that helps to detect and mitigate certain types of attacks, including Cross-Site Scripting (XSS) and data injection attacks.

Why You Need a Strict CSP

Without a CSP, browsers will execute any script loaded on your page, regardless of its origin. This is the root cause of XSS. By implementing a strict CSP, you instruct the browser to only execute scripts from trusted sources.

Core Directives

  • default-src: Serves as a fallback for the other fetch directives.
  • script-src: Specifies valid sources for JavaScript.
  • style-src: Specifies valid sources for stylesheets.
  • img-src: Specifies valid sources of images and favicons.
  • connect-src: Restricts the URLs which can be loaded using script interfaces (like fetch or XMLHttpRequest).

The Problem with 'unsafe-inline'

Many developers get frustrated with CSP and resort to using 'unsafe-inline' for scripts or styles. This completely defeats the purpose of CSP against XSS. Instead, you should use:

  1. Nonces: Cryptographically strong random numbers generated on the server and passed to the script tag.
  2. Hashes: Cryptographic hashes of the inline script's content.

Example: A Strong Default

Content-Security-Policy: default-src 'self'; script-src 'self' 'nonce-rAnd0m'; style-src 'self' 'nonce-rAnd0m'; object-src 'none'; base-uri 'none'; require-trusted-types-for 'script';

You can easily generate complex CSP rules tailored to your framework using our CSP Header Generator.