3.4.3.3 What is a Nonce?

Learn about a nounce and how it works.

A nonce (or number used once) is a cryptographic term referring to a number or value that is used only once in a secure communication. When it comes to web security, particularly with Content Security Policy (CSP), a nonce attribute is used to allow specific inline scripts to be executed.

Here’s how a nonce works:

  1. CSP and Nonce - When you define a Content Security Policy (CSP) for your web application, you can specify that only scripts with a specific nonce value are allowed to execute. This prevents attackers from injecting malicious scripts because they won’t have access to the nonce value.
  2. Implementation - The server generates a unique nonce value for each request and includes it in the CSP header. Inline scripts that should be allowed to run must include this nonce value in their script tag.

Consider the following nonce examples.

HTML (Inline Script with Nonce)

<script nonce="random12345">
    console.log('This script will run because it has the correct nonce.');
</script>

HTML (Inline Script without Nonce)

<script>
    console.log('This script will be blocked by CSP because it lacks the correct nonce.');
</script>

In this example, the script with the correct nonce random12345 will be allowed to execute, while other scripts will be blocked, enhancing the security of your web application. You have to look at the browser console to see the remaining violations.