Skip to content

Commit

Permalink
docs: example of generated nonce to use base64 encoding as per spec (#…
Browse files Browse the repository at this point in the history
…55039)

nonce's are limited to characters found in base64 encoding, uuids contain '-' which breaks the spec,
converting to a base64 string after generating simplifies this

---

This was a bit gotcha in our project, there are a few tools that only expect there to be a single `-` and do a split based off it (so when there are >1 they fail)

## Rules for nonce's

- The nonce must be unique for each HTTP response
- The nonce should be generated using a cryptographically secure random generator
- The nonce should have sufficient length, aim for at least 128 bits of entropy (32 hex characters, or about 24 base64 characters).
- Script tags that have a nonce attribute must not have any untrusted / unescaped variables within them.
- The characters that can be used in the nonce string are limited to the characters found in base64 encoding.
  • Loading branch information
csi-lk committed Sep 6, 2023
1 parent 10b1865 commit cc34ea5
Showing 1 changed file with 2 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ For example:
import { NextRequest, NextResponse } from 'next/server'

export function middleware(request: NextRequest) {
const nonce = crypto.randomUUID()
const nonce = Buffer.from(crypto.randomUUID()).toString('base64')
const cspHeader = `
default-src 'self';
script-src 'self' 'nonce-${nonce}' 'strict-dynamic';
Expand Down Expand Up @@ -76,7 +76,7 @@ export function middleware(request: NextRequest) {
import { NextResponse } from 'next/server'

export function middleware(request) {
const nonce = crypto.randomUUID()
const nonce = Buffer.from(crypto.randomUUID()).toString('base64')
const cspHeader = `
default-src 'self';
script-src 'self' 'nonce-${nonce}' 'strict-dynamic';
Expand Down

0 comments on commit cc34ea5

Please sign in to comment.