Course contentsShow
← Security
Lesson 661 of 3,05214. Web Security - XSS and Content InjectionFree lesson

Nonces and Hashes for Inline Content

Using cryptographic nonces and hashes to safely allow specific inline scripts and styles.

Nonces and Hashes for Inline Content

You'll learn how to safely allow specific inline scripts and styles without weakening your Content Security Policy.

The Core Problem

You've learned that CSP can block inline scripts and styles to prevent XSS. But what if you legitimately need some inline JavaScript or CSS in your page? Blocking everything inline is secure but sometimes impractical. This is where nonces and hashes come in—they act like VIP passes for specific inline content.

Cryptographic Nonces

A nonce (number used once) is a random, unpredictable value generated server-side for each page load. You add it to both your CSP header and the inline content you want to allow:

Content-Security-Policy: script-src 'nonce-r4nd0mV4lu3H3r3'

Then in your HTML:

<script nonce="r4nd0mV4lu3H3r3">
  console.log("This inline script is allowed!");
</script>

Analogy: Think of it like a concert wristband with a unique code that changes every show. Only attendees with today's specific code get in—attackers can't forge it because they don't know what code your server generated.

Content Hashes

Alternatively, you can use a hash of the exact inline content:

Content-Security-Policy: script-src 'sha256-abc123...'

The browser calculates the hash of each inline script and only executes it if the hash matches. This works great for static inline content that doesn't change.

Why This Works

Attackers injecting XSS payloads don't know your random nonce or the exact hash of approved content, so their injected scripts won't execute—even though your legitimate inline code does.

Key Takeaway: Nonces and hashes let you whitelist specific inline scripts and styles in CSP by using cryptographic verification, maintaining security while allowing necessary inline content.