0Pricing
OAuth2 & OpenID Connect Deep Dive · Lección

Uso de nonce para evitar repeticiones

Aprenda cómo el parámetro nonce de OpenID Connect vincula un token de ID con una solicitud de autenticación específica y protege contra ataques de repetición de tokens.

Uso de nonce para evitar repeticiones es una lección gratuita de OAuth2 & OpenID Connect Deep Dive en CoddyKit. Esta es la lección 4 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de OAuth2 & OpenID Connect Deep Dive, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de OAuth2 & OpenID Connect Deep Dive incluye 4 lecciones en total.

Partes de esta lección aún no han sido traducidas y se muestran en inglés.

What Is the nonce?

The nonce is a random value the client generates and includes in the authentication request. The OpenID Provider echoes it back inside the issued ID token. Matching them proves the token belongs to this request.

The Replay Threat

Without a nonce, an attacker who captures a valid ID token (for example, in the Implicit or Hybrid flow where tokens travel via the browser) could replay it into another session. The nonce ties the token to one specific request, defeating replay.

nonce vs state

They are different tools:

  • state — protects the OAuth2 authorization request/response against CSRF.
  • nonce — protects the ID token against replay, validated inside the token itself.

Use both together in OIDC flows.

Generating a nonce

Create a high-entropy random value and store it bound to the user's session before redirecting.

import secrets
nonce = secrets.token_urlsafe(32)
session['oidc_nonce'] = nonce
print(nonce)

Including It in the Request

Add the nonce to the authorization request alongside the usual parameters.

GET /authorize?
  response_type=code
  &client_id=app123
  &scope=openid profile
  &redirect_uri=https://app.example.com/cb
  &state=xyz
  &nonce=Tk9SQ0VfdmFsdWU

It Comes Back in the ID Token

The ID token's payload includes the exact nonce you sent.

{
  "iss": "https://op.example.com",
  "sub": "248289",
  "aud": "app123",
  "nonce": "Tk9SQ0VfdmFsdWU",
  "exp": 1735689600
}

Validating the nonce

After validating the ID token's signature and claims, compare its nonce with the value stored in the session.

if id_token['nonce'] != session.pop('oidc_nonce', None):
    raise Exception('nonce mismatch - reject token')

When nonce Is Required

The nonce is mandatory in the Implicit and Hybrid flows because ID tokens are returned through the browser front channel. In the Authorization Code flow it is recommended and strongly encouraged.

One-Time Use

Treat each nonce as single-use. Remove it from the session as soon as it is validated so the same value can never authorize a second token, closing replay windows.

Common Mistakes

Pitfalls to avoid:

  • Using a predictable or reused nonce.
  • Forgetting to compare it after validating the signature.
  • Storing it client-side without integrity protection.
  • Skipping it in front-channel flows.

Putting It Together

The full lifecycle: generate nonce, store in session, send in auth request, receive it in the ID token, verify signature and claims, then compare and discard the nonce. Only then trust the authentication.

Quick Check

Test your knowledge of the nonce.

Recap

The nonce protects ID tokens from replay.

  • Generate a random nonce, store it in session, send it in the auth request.
  • The OP echoes it inside the ID token.
  • Validate by comparing token nonce to session nonce, then discard it.
  • Required in Implicit/Hybrid flows; recommended everywhere.

Preguntas frecuentes

¿La lección «Uso de nonce para evitar repeticiones» es gratis?

Sí — el texto completo de «Uso de nonce para evitar repeticiones» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de OAuth2 & OpenID Connect Deep Dive, actualiza a CoddyKit PRO. El curso de OAuth2 & OpenID Connect Deep Dive incluye 4 lecciones en total.

¿Qué aprenderé en «Uso de nonce para evitar repeticiones»?

Aprenda cómo el parámetro nonce de OpenID Connect vincula un token de ID con una solicitud de autenticación específica y protege contra ataques de repetición de tokens. Practicas OAuth2 & OpenID Connect Deep Dive con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.

¿Necesito experiencia previa para empezar OAuth2 & OpenID Connect Deep Dive?

No se requiere experiencia previa. OAuth2 & OpenID Connect Deep Dive en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 4 de 4.

¿Cuánto tiempo toma la lección «Uso de nonce para evitar repeticiones»?

La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.

¿Puedo escribir y ejecutar código en esta lección de OAuth2 & OpenID Connect Deep Dive?

Sí. Cada lección de OAuth2 & OpenID Connect Deep Dive incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.

Todas las lecciones de este curso

  1. Flujo de código de autorización con OIDC
  2. Flujo implícito con OIDC
  3. Flujo híbrido con OIDC
  4. Uso de nonce para evitar repeticiones
← Volver a OAuth2 & OpenID Connect Deep Dive