0Pricing
Spring Security 6 & JWT Authentication · Lección

Expiración de JWT y reglas de validación

Comprenda cómo se controla la duración de un JWT mediante claims temporales como exp, nbf e iat, y cómo los validadores rechazan tokens expirados o prematuros.

Expiración de JWT y reglas de validación es una lección gratuita de Spring Security 6 & JWT Authentication 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 Spring Security 6 & JWT Authentication, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de Spring Security 6 & JWT Authentication incluye 4 lecciones en total.

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

Why Tokens Need a Lifetime

A JWT is a bearer credential: whoever holds it is trusted. If a token never expired, a leaked token would grant access forever.

Time-based claims limit the damage window by making tokens valid only for a short period.

The exp Claim

The exp (expiration) claim is a Unix timestamp. After this moment the token is invalid and must be rejected.

{
  'sub': 'user123',
  'exp': 1717200000
}

The iat Claim

The iat (issued at) claim records when the token was created. It is useful for measuring token age and for revoking all tokens issued before a certain time.

{
  'sub': 'user123',
  'iat': 1717196400,
  'exp': 1717200000
}

The nbf Claim

The nbf (not before) claim defines the earliest time a token becomes valid. A token used before its nbf time must be rejected, which is handy for tokens scheduled to activate later.

{
  'sub': 'user123',
  'nbf': 1717196400,
  'exp': 1717200000
}

Choosing an Expiration Window

Short lifetimes are safer but force frequent re-authentication. A common pattern is:

  • Access token: 5-15 minutes
  • Refresh token: days or weeks

The short access token limits exposure; the refresh token keeps the user logged in.

Setting exp When Issuing

When you build a token, set exp relative to now. Here a 15-minute access token is created using a JWT library.

const now = Math.floor(Date.now() / 1000);
const payload = {
  sub: 'user123',
  iat: now,
  exp: now + 15 * 60
};

Validating exp on the Server

On every request the server checks exp against the current time. Most libraries do this automatically and throw if the token is expired.

try {
  const claims = verify(token, secret);
} catch (err) {
  if (err.name === 'TokenExpiredError') {
    // reject with 401
  }
}

Clock Skew

Servers do not always have perfectly synchronized clocks. A small leeway (a few seconds) prevents valid tokens from being rejected because of minor clock differences.

verify(token, secret, { clockTolerance: 5 });

exp Is Not Encryption

Remember: a JWT payload is only encoded, not encrypted. The exp claim stops the server from accepting the token, but anyone can read the claims. Never put secrets in the payload.

Reacting to Expiry on the Client

When the client gets a 401 due to expiry, it should silently request a new access token using the refresh token, then retry the original request.

if (response.status === 401) {
  const fresh = await refreshAccessToken();
  return retryWith(fresh);
}

Common Validation Mistakes

Watch out for these errors:

  • Forgetting to validate exp at all
  • Using milliseconds instead of seconds for the timestamp
  • Setting an excessively long lifetime
  • Ignoring nbf, allowing premature use

Quick Check

Test your knowledge of JWT time claims.

Recap

You learned how JWT lifetime is controlled:

  • exp sets the expiration; iat records issue time; nbf sets earliest validity
  • Use short access tokens plus longer refresh tokens
  • Allow small clock skew with leeway
  • exp does not encrypt the payload

Proper expiration handling keeps stolen tokens useful for only a brief window.

Preguntas frecuentes

¿La lección «Expiración de JWT y reglas de validación» es gratis?

Sí — el texto completo de «Expiración de JWT y reglas de validación» 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 Spring Security 6 & JWT Authentication, actualiza a CoddyKit PRO. El curso de Spring Security 6 & JWT Authentication incluye 4 lecciones en total.

¿Qué aprenderé en «Expiración de JWT y reglas de validación»?

Comprenda cómo se controla la duración de un JWT mediante claims temporales como exp, nbf e iat, y cómo los validadores rechazan tokens expirados o prematuros. Practicas Spring Security 6 & JWT Authentication 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 Spring Security 6 & JWT Authentication?

No se requiere experiencia previa. Spring Security 6 & JWT Authentication 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 «Expiración de JWT y reglas de validación»?

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 Spring Security 6 & JWT Authentication?

Sí. Cada lección de Spring Security 6 & JWT Authentication 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. Comprensión de los JSON Web Tokens
  2. Estructura y claims de los JWT
  3. Firma y verificación de JWT
  4. Expiración de JWT y reglas de validación
← Volver a Spring Security 6 & JWT Authentication