liveBook · Manning

Nonce

As explained in Building Web APIs with ASP.NET Core

A script nonce is a cryptographically unpredictable token that authorizes a specific inline script under a content security policy.

A script nonce is a random, cryptographically unpredictable identifier. A Content-Security-Policy header permits an inline script only when its script element carries the same nonce value. section 12.4.4

Apply a nonce when a narrowly permitted inline script is required:

  • Add the nonce to the script-src directive in the Content-Security-Policy response header. section 12.4.4
  • Set the identical nonce value in the inline script element returned by the endpoint. section 12.4.4
  • Redeploy the application and verify that the browser executes the permitted script. section 12.4.4

Permitting one test script

The /cod/test Minimal API endpoint returns an inline script with a nonce, while the CSP header allows that same nonce. The browser alert then runs after redeployment. Avoid this pattern in production unless on-demand inline code is genuinely necessary, because it weakens the policy’s purpose. section 12.4.4

Refused to execute inline script because it violates the following Content Security Policy directive: "default-src ' self' ". Either the ‘unsafe-inline’ keyword, a hash (‘sha256-j3kW1ylRRXx1+pINyR/6EW435UHoxKSlU6fhd5xVSSk=‘), or a nonce (' nonce-...' ) is required to enable inline execution. Note also that ' script-src'  was not explicitly set, so ' default-src'  is used as a fallback.

Use the browser console violation to diagnose a blocked inline script and identify when a hash or nonce is required. section 12.4.4

How Building Web APIs with ASP.NET Core covers it

How deep it goes
Defines the nonce, applies matching values in the policy and script element, and warns against production inline scripts.
Examples
Demonstrates a nonce in Program.cs for /cod/test and verifies the resulting JavaScript alert after redeployment.
What it assumes
Assumes a deployed web API with a Content-Security-Policy header and an inline script endpoint.
What you can do after
Apply it via a Content-Security-Policy header and matching script attribute, then verify browser execution after redeployment.
How it connects
Connects Content-Security-Policy, HTTP security headers, inline scripts, browsers, and deployment testing.

Also explained in

Compare how 4 books explain nonce →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Building Web APIs with ASP.NET Core. The section links point to the parts of the book it draws on.