What Is a Nonce in Security? Nonce vs State vs PKCE

Markaretta DofourMarkaretta DofourUpdated 14 min read

A nonce is a “number used once”: a random or unique value added to a message or request so that an attacker cannot replay or reuse it. In OpenID Connect logins, your application sends a nonce and checks it in the ID token, state protects the callback against cross-site request forgery (CSRF), and PKCE binds the authorization code to the client that asked for it.

NIST’s glossary defines a nonce as “a value that is used only once within a specified context” and, in another of its sources, as “a random or non-repeating value that is included in data exchanged by a protocol” (NIST CSRC glossary, nonce). You meet the word in encryption, in browser security headers, in Bitcoin mining and in login code, and the rules for it differ from one place to the next.

Key takeaways

  • A nonce is a value used once in a given context, so a receiver can reject a copy of an old message. NIST lists both random values and non-repeating values such as counters (NIST).
  • Nonces are generated randomly, sequentially (a counter) or as a hybrid of both. TLS 1.3, for example, builds each record’s nonce from a sequence number combined with a static write value (RFC 8446, section 5.3).
  • In an OpenID Connect login, the nonce binds the ID token to your login attempt, state binds the callback to the browser session, and PKCE makes a stolen authorization code useless without the verifier.

What is a nonce, in plain words?

A nonce is a value that a protocol promises to use only once in a particular context, such as one login attempt, one web page response or one encrypted message under one key. Because the value never repeats in that context, a receiver that remembers or checks it can spot a message that has been seen before. The name is usually read as “number used once”, although a nonce does not have to be a small number: OpenID Connect, for example, defines its nonce as a string value.

The main thing a nonce defends against is a replay attack. NIST describes it as an attack in which the attacker is “able to replay previously captured messages” between a legitimate user and a verifier “to masquerade as that claimant to the verifier or vice versa” (NIST CSRC glossary, replay attack). One of NIST’s nonce definitions says exactly this: a nonce is “a randomly generated value used to defeat ‘playback’ attacks in communication protocols” (NIST).

A nonce does not need to be secret to do its job, since NIST notes that it “can be a secret or non-secret value” (NIST). Some uses, such as login and CSP nonces, also need a value that nobody could predict before it was issued, while others, such as encryption counters, need a value that does not repeat. A value attached to a message proves nothing until the receiver checks it, so for any nonce you meet, ask who creates it, where it travels and who checks it.

Key terms you will meet next to nonces

These words often appear on the same page as “nonce”, and they are easy to mix up:

  • Replay attack: resending a captured, valid message so that the receiver acts on it again, as defined above.
  • Freshness: the property that a message belongs to the current exchange and is not an old copy. A nonce gives a receiver a way to test freshness.
  • Salt: NIST calls a salt “a non-secret value used in a cryptographic process, usually to ensure that the results of computations for one instance cannot be reused by an attacker” (NIST CSRC glossary, salt). For passwords, NIST’s guidance says both “the salt value and the resulting hash SHALL be stored for each password” (NIST SP 800-63B), so a salt stays with its stored hash, while a nonce is meant for one use in its context. Related post: What Is a Rainbow Table Attack and How Salting Stops It.
  • Initialization vector (IV): a starting input for some encryption modes. In the GCM encryption mode, NIST defines the IV as “a nonce that is associated with an invocation of authenticated encryption on a particular plaintext and AAD”, where AAD means additional authenticated data (NIST CSRC glossary, initialization vector), so in that context an IV simply is a nonce.

How is a nonce generated?

There are three common ways to produce a nonce, and the right one depends on what the protocol needs: unpredictability, guaranteed uniqueness, or both.

Type How it works Strength Where you see it
Random nonce Draw enough bits from a cryptographically secure random number generator that a repeat is practically impossible. Wikipedia notes nonces are “generated with enough random bits to ensure an insignificantly low chance of repeating a previously generated value” (Wikipedia, cryptographic nonce). Unpredictable, so an attacker cannot guess the next one. OpenID Connect login nonces, CSP script nonces, TLS handshake random values (RFC 8446, section 4.1.2).
Sequential (counter) nonce Start at a value and add one for every message. NIST’s definitions include “non-repeating” values, not only random ones (NIST). Does not repeat until the counter wraps, but anyone can work out the next value. The 64-bit record sequence number in TLS 1.3, which goes up by one for each record (RFC 8446, section 5.3).
Hybrid nonce Combine a counter with a random or secret value, or add a timestamp. Wikipedia notes that “many nonces also include a timestamp to ensure exact timeliness”, which needs synchronized clocks (Wikipedia). The counter keeps values from repeating, and the added value means the nonce is not a bare count. TLS 1.3 record nonces, described below.

TLS 1.3 is a good example of the hybrid approach. Each encrypted record’s nonce is the 64-bit record sequence number, padded and then “XORed with either the static client_write_iv or server_write_iv” (RFC 8446, section 5.3), so the counter keeps the nonce from repeating under one key and the static value keeps it from being a bare count. The same RFC says that if an implementation would need to wrap the sequence number, it must rekey or close the connection, which is how it keeps the “never repeated with the same key” promise that NIST’s SP 800-53 definition asks for (NIST).

A predictable counter can be fine in encryption: RFC 8439, which defines the ChaCha20-Poly1305 cipher, says “counters and LFSRs are both acceptable ways of generating unique nonces” (RFC 8439, section 4). It is the wrong choice for a login nonce, which OpenID Connect says must be “unguessable to attackers” (OIDC Core, nonce notes), or for a CSP nonce, which MDN says should come from a secure random generator (MDN, nonce attribute).

What are the benefits of using a nonce?

Depending on how a protocol uses and checks it, a nonce can give that protocol three properties. NIST describes the first two as “guaranteeing the transmittal of live data rather than replayed data, thus detecting and protecting against replay attacks” (NIST):

  • Replay protection: a captured message can be refused, because its nonce has already been used or does not match the pending exchange.
  • Freshness: the receiver can tell that the reply belongs to the request it just sent, not to an older exchange.
  • Uniqueness: two messages under one key do not share a nonce, which matters in encryption: in ChaCha20-Poly1305, a repeated nonce “reveals the XOR of the plaintexts” (RFC 8439, section 4).

You already rely on this idea every day. A time-based one-time password works much like a nonce for your sign-in, since the standard says the verifier “MUST NOT accept the second attempt of the OTP” after the first has been validated (RFC 6238, section 5.2).

How do TLS, CSP and Bitcoin use nonces?

The same word covers quite different jobs, so check the protocol’s own rules before you apply advice from one context to another.

Context What the nonce does What to keep in mind
TLS The ClientHello and ServerHello each carry “32 bytes generated by a secure random number generator” (RFC 8446, section 4.1.2 and section 4.1.3), and each encrypted record uses the hybrid nonce described above. TLS defines these values itself, and they are separate from the OpenID Connect nonce described below.
Content Security Policy (CSP) A random value in the CSP header that must also appear on an inline script or style element before the browser runs it. MDN says nonces “should be generated differently each time the page loads” and recommends at least 128 bits from a secure random generator (MDN, nonce attribute). Generate a new one for every response. Related post: Entra ID Will Block Login Script Injection: Harden Keycloak CSP.
Bitcoin mining A 4-byte field in the block header that is “an arbitrary number miners change to modify the header hash in order to produce a hash less than or equal to the target threshold” (Bitcoin Developer Reference, block headers). This nonce is about work, not secrecy, as the next section explains.

How does a nonce work in hashing and proof of work?

In a proof-of-work system, the nonce is an input the worker changes while searching for a hash that meets a condition, and in Bitcoin that condition is a header hash less than or equal to the target (Bitcoin Developer Reference). Wikipedia sums up why this is useful: nonces “vary the input to a cryptographic hash function”, which makes it “far more difficult to create a ‘desirable’ hash than to verify it” (Wikipedia). When all 32-bit values have been tried, the Bitcoin reference says “the time can be updated or the coinbase transaction can be changed” to get a fresh header to search (Bitcoin Developer Reference).

What is the difference between nonce, state and PKCE?

In an OpenID Connect login, three different values protect three different steps. OpenID Connect (OIDC) is the identity layer built on OAuth 2.0, and it adds an ID token, a signed token from the identity provider with claims about the login (OIDC Core, ID token). The nonce protects that ID token, state protects the redirect back to your application, and PKCE (Proof Key for Code Exchange) protects the exchange of the authorization code for tokens.

Nonce State PKCE
What it protects against An ID token replayed or injected into the wrong login CSRF: an attacker forcing your browser to complete a login callback they started Someone redeeming an intercepted authorization code
Who creates it Your application, fresh for each login Your application, fresh for each login Your application creates a secret code_verifier and sends its hash as code_challenge
Where it travels Authorization request, then back inside the ID token Authorization request, then back on the callback URL Challenge in the authorization request, verifier in the token request
Who checks it Your application, against the ID token’s nonce claim Your application, on the callback The authorization server, at the token endpoint
Specification OIDC Core, ID token validation RFC 6749, section 10.12 RFC 7636, section 4

OpenID Connect Core says that if a nonce was sent in the authentication request, “a nonce Claim MUST be present” in the ID token and its value checked against the one sent (OIDC Core, ID token validation). Its implementation notes add that the nonce needs to carry per-session state and be unguessable, and suggest that a web server store a random value in an HttpOnly session cookie and send its hash as the nonce (OIDC Core, nonce notes).

The protections overlap in places. The OAuth Security Best Current Practice says clients that have made sure the authorization server supports PKCE may rely on the CSRF protection PKCE provides, that the OIDC nonce also provides CSRF protection, and that otherwise one-time CSRF tokens in state must be used (RFC 9700, section 2.1). A nonce cannot stop someone from redeeming a stolen code from a public client directly at the token endpoint, though, and PKCE can (RFC 9700, section 4.5.3). We suggest keeping all three checks explicit, because each one is tied to a different step of the login. For background on the token types, see our ID token versus access token guide, and for picking a flow in the first place, our guide to choosing the best authorization flows for your app.

Follow the values through a Keycloak login

The animation below shows where each value is created and checked during one login against Keycloak, using the authorization code flow from RFC 6749, section 4.1, with the checks that RFC 7636, section 4.6 and OIDC Core assign to each side. The Keycloak Server Administration Guide documents the authorization code flow and support for PKCE.

Where state, nonce and PKCE are checked in one login: the app stores all three, the callback state is checked, Keycloak checks the code verifier, and the app checks the nonce in the ID token

Your app stores a state, a nonce and a code verifier (1) and sends the state, the nonce and the code challenge to Keycloak (2). The callback brings back the code and the same state, which your app checks (3). Your app sends the code with the verifier, which Keycloak checks against the challenge (4), and the returned ID token carries the nonce, which your app checks before signing the user in (5).

In practice, a client library such as the Keycloak JavaScript adapter can manage much of this transaction for you. The snippets below expose the values so you can review what your library does; they are not a complete login implementation.

Create the values and send the request

Generate the three values independently for every login attempt and store them together, keyed by the state value, along with the expected issuer, client ID and redirect URI. In the browser, crypto.getRandomValues gives cryptographically strong random bytes, and this example uses the 32 random bytes that RFC 7636, section 4.1 recommends for the verifier:

function randomValue() {
  const bytes = crypto.getRandomValues(new Uint8Array(32));
  return btoa(String.fromCharCode(...bytes))
    .replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
}

const state = randomValue();
const nonce = randomValue();
const codeVerifier = randomValue();

For the S256 method, the code challenge is the base64url-encoded SHA-256 hash of the verifier (RFC 7636, section 4.2). The request to Keycloak’s authorization endpoint then looks like this, wrapped for reading, with capitalized placeholders for the generated values:

https://identity.example.com/realms/demo/protocol/openid-connect/auth
  ?client_id=web-app
  &response_type=code
  &scope=openid
  &redirect_uri=https%3A%2F%2Fapp.example.com%2Fcallback
  &state=STATE
  &nonce=NONCE
  &code_challenge=CHALLENGE
  &code_challenge_method=S256

Check the callback and redeem the code

When the browser comes back, look up the pending attempt by state and reject the callback if it is missing, different or already used. The authorization response must carry “the exact value received from the client” in state (RFC 6749, section 4.1.2). Then send the code to the token endpoint with the stored redirect URI (RFC 6749, section 4.1.3) and the code_verifier (RFC 7636, section 4.5). The authorization server, Keycloak here, hashes the verifier and must return an invalid_grant error if it does not match the challenge (RFC 7636, section 4.6).

Patched on the day, not on your next maintenance window

Keycloak 26.7.2 fixed CVE-2026-18963, an account takeover through password reset. Skycloak had it available for auto-upgrade and told customers the same day upstream shipped it. Self-hosted teams schedule that work themselves.

How do you validate the nonce in an ID token?

Compare the ID token’s nonce claim with the value you stored before the redirect, and reject the login if it is missing or different. Do this only after your library has checked the token’s signature, issuer, audience and expiry, because a decoded token is just readable data until it is validated (OIDC Core, ID token validation):

function assertNonce(validatedClaims, expectedNonce) {
  if (typeof expectedNonce !== "string" || expectedNonce.length === 0) {
    throw new Error("No pending login nonce");
  }
  if (typeof validatedClaims.nonce !== "string" ||
      validatedClaims.nonce !== expectedNonce) {
    throw new Error("ID token nonce mismatch");
  }
}

Do not create the user’s session or use any returned token until this check passes, and mark the attempt as consumed so a second callback cannot reuse it. The OAuth security guidance says a client using the nonce against code injection must validate it in the ID token from the token endpoint and ensure that, “unless and until that check succeeds, all tokens (ID Tokens and the access token) are disregarded and not used for any other purpose” (RFC 9700, section 4.5.3.2).

OpenID Connect defines the nonce check on the ID token (OIDC Core), so that is the token to read, not the access token your API receives. To check access tokens on the server side, see verifying a Keycloak-issued access token on the backend, and for the wider rules on handling tokens, our JWT best practices for developers.

How do you require PKCE and the nonce in Keycloak?

On the server side, set the client’s PKCE method to S256. The Keycloak Server Administration Guide lists this setting under Capability Config and says it lets you “specify which PKCE challenge method is required for this client”. When it is blank, “Keycloak does not apply PKCE unless the client sends the appropriate PKCE parameters”, so PKCE is possible but not required, while with S256 Keycloak applies PKCE with that challenge method to the client. The same section says Standard Flow lets the client use the authorization code flow (Keycloak Server Administration Guide):

  1. Select your realm, open Clients and select the OIDC client.
  2. Make sure Standard flow is enabled and the redirect URI is the one your application uses.
  3. In Capability config, set PKCE method to S256 and save.

Related post: Keycloak: How To Create A PKCE Authorization Flow Client?.

On the application side, the keycloak-js adapter uses a nonce by default: its useNonce option “adds a cryptographic nonce to verify that the authentication response matches the request (default is true)”, and pkceMethod defaults to S256 (Keycloak JavaScript adapter). Check that your init options do not set either to false. The PKCE setting acts at Keycloak’s endpoints, while OpenID Connect makes the nonce check part of the client’s validation of the ID token (OIDC Core), so your application still needs that check.

Verify the failure cases before shipping

Use a test realm and client to prove that bad transactions fail, not only that good logins succeed:

  • Change or remove the callback’s state and confirm your application rejects it.
  • Feed your nonce check validated test claims with a missing or different nonce and confirm it rejects them.
  • Replay a completed callback and confirm the transaction cannot be reused.
  • Send a fresh authorization request without a code challenge and confirm that the client configured with S256 gets no authorization code, since that setting names the PKCE challenge method “required for this client” (Keycloak Server Administration Guide).
  • Redeem a fresh code with the wrong verifier and confirm no tokens are issued.

These checks fit naturally into a wider review such as our enterprise IAM security checklist, and if you are still getting clear on how login relates to permissions, our guide to authorization is a good companion.

Frequently asked questions

Is a nonce always random?

No. NIST’s definitions include non-repeating values such as counters as well as random ones (NIST). Encryption can use counters where the requirement is a unique value (RFC 8439, section 4), but a login nonce has to be unguessable (OIDC Core, nonce notes), so a counter is not a safe substitute there, and MDN asks for secure random values in a CSP nonce.

What is the difference between a nonce and a salt?

For passwords, a salt is stored alongside the resulting hash for each password (NIST SP 800-63B), so it stays with that stored value. A nonce belongs to a single exchange or message and is not supposed to be used again in that context.

Does a nonce replace state or PKCE?

No. Some CSRF protections overlap, but a nonce does not stop a stolen code from a public client being redeemed at the token endpoint, which is PKCE’s job (RFC 9700, section 4.5.3). Follow your library’s documented flow before you remove any of the three.

Why does the nonce match but login still fail?

The nonce is one check among several. An expired ID token, the wrong issuer, the wrong audience or an invalid signature will still fail validation (OIDC Core), so read the validation error rather than turning nonce checks off.

Sources

Check your own login flow next

Go through one login in your application and confirm that it sends and validates a nonce, a state and a PKCE challenge on every request, using the failure cases above. To see the nonce for yourself, sign in to a test client and paste the ID token into our JWT decoder, which runs in your browser, and check that the nonce claim is there and matches what your application sent; keep the real validation in your application. For the broader login setup on Skycloak, see our single sign-on feature. If you would rather not run the Keycloak server behind it yourself, you can read about managed Keycloak hosting on Skycloak.

Patched on the day, not on your next maintenance window

Keycloak 26.7.2 fixed CVE-2026-18963, an account takeover through password reset. Skycloak had it available for auto-upgrade and told customers the same day upstream shipped it. Self-hosted teams schedule that work themselves.

Markaretta Dofour
Written by
Content Writer, Skycloak

Markaretta is Skycloak's content writer. She proposes topics, writes posts and pages for search and AI answers, and watches how they perform. She keeps to the answer first and never uses a number or quote without its source.

© 2026 Skycloak. All Rights Reserved. Design by Yasser SolimanKeycloak™ is a trademark of the Linux Foundation. Skycloak is not affiliated with the Keycloak project.