Understanding CSP Nonces
You'll learn how nonces provide a secure way to allow specific inline scripts while blocking all others.
The Problem with Inline Scripts
You've already learned that CSP's 'unsafe-inline' keyword allows all inline scripts to run—including malicious ones injected by attackers. This defeats the entire purpose of Content Security Policy. But what if you legitimately need some inline scripts on your page?
What Is a Nonce?
A nonce (number used once) is a random, unique token generated on the server for each page load. Think of it like a one-time password that expires immediately—attackers can't predict or reuse it.
Instead of allowing all inline scripts with 'unsafe-inline', you:
- Generate a cryptographically random nonce value for each request
- Include it in your CSP header:
script-src 'nonce-abc123xyz' - Add the same nonce to trusted inline scripts:
<script nonce="abc123xyz">
How It Works
When the browser sees your CSP policy with a nonce, it only executes inline scripts that have a matching nonce attribute. Any injected script without the correct nonce—which attackers can't know—gets blocked.
Analogy: It's like a VIP wristband at a concert. The venue (your server) prints unique wristbands for each show. Only people wearing today's specific wristband get in. Yesterday's wristband? Blocked. No wristband? Blocked.
Why Nonces Matter
Nonces let you keep the security benefits of CSP while using inline scripts where necessary. Each nonce is:
- Unpredictable: Generated with cryptographic randomness
- Single-use: Different for every page load
- Impossible to forge: Attackers can't inject the right value
Key Takeaway: Nonces are randomly generated tokens that whitelist specific inline scripts by matching a server-provided value, allowing secure inline code without enabling 'unsafe-inline'.