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

Rotación de claves de firma y gestión de claves

Aprenda por qué y cómo rotar de forma segura las claves de firma de JWT usando identificadores de clave (kid), conjuntos JWK y validez solapada para evitar interrupciones.

Rotación de claves de firma y gestión de claves 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 Rotate Keys?

A signing key is the secret that proves a JWT is genuine. If it leaks, an attacker can forge tokens. Key rotation replaces keys periodically so a compromised key has a limited lifetime.

The Rotation Challenge

You cannot simply swap the key: tokens signed with the old key are still valid until they expire. The server must accept the old and new keys at the same time during a transition window.

The kid Header

The JWT header can carry a kid (key ID). It tells the verifier which key signed this token, so the server can look up the right key among several.

{
  'alg': 'RS256',
  'typ': 'JWT',
  'kid': 'key-2024-06'
}

Signing With a kid

When you mint a token, stamp the current key's id into the header so verifiers can find the matching public key later.

const token = sign(payload, privateKey, {
  algorithm: 'RS256',
  keyid: 'key-2024-06'
});

Keeping a Key Map

The server holds a map of kid to key. During rotation it contains both the retiring key and the new key.

const keys = {
  'key-2024-06': newPublicKey,
  'key-2024-03': oldPublicKey
};

Verifying by kid

On verification, read the kid from the header, select the key, then validate the signature against it.

const header = decodeHeader(token);
const key = keys[header.kid];
const claims = verify(token, key, { algorithms: ['RS256'] });

JWK and JWKS

A JWK (JSON Web Key) is a public key in JSON form. A JWKS (JWK Set) is a list of them, typically served at a well-known URL so resource servers can fetch current public keys automatically.

{
  'keys': [
    { 'kid': 'key-2024-06', 'kty': 'RSA', 'n': '...', 'e': 'AQAB' }
  ]
}

Spring Security JwtDecoder from JWKS

A Spring resource server can build a decoder straight from a JWKS endpoint, so rotation requires no redeploy of clients.

JwtDecoder decoder = NimbusJwtDecoder
    .withJwkSetUri('https://auth.example.com/.well-known/jwks.json')
    .build();

The Rotation Timeline

A safe rotation follows phases:

  • Publish the new key in the JWKS, but keep signing with the old key
  • Switch signing to the new key
  • Wait for all old tokens to expire
  • Remove the old key

Asymmetric vs Symmetric

Rotation is easier with asymmetric keys (RS256/ES256): you can share public keys freely via JWKS while keeping the private key secret. Symmetric (HS256) requires distributing the shared secret to every verifier.

Storing Private Keys Safely

Never commit signing keys to source control. Store them in a secrets manager (Vault, AWS Secrets Manager, KMS) and load them at runtime. Limit who and what can read them.

Quick Check

Test your understanding of key rotation.

Recap

You learned to rotate JWT signing keys safely:

  • Rotation limits the damage of a leaked key
  • Use kid headers so multiple keys can coexist
  • Publish public keys via a JWKS endpoint
  • Rotate in phases and store private keys in a secrets manager

Asymmetric keys plus JWKS make rotation seamless and downtime-free.

Preguntas frecuentes

¿La lección «Rotación de claves de firma y gestión de claves» es gratis?

Sí — el texto completo de «Rotación de claves de firma y gestión de claves» 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 «Rotación de claves de firma y gestión de claves»?

Aprenda por qué y cómo rotar de forma segura las claves de firma de JWT usando identificadores de clave (kid), conjuntos JWK y validez solapada para evitar interrupciones. 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 «Rotación de claves de firma y gestión de claves»?

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. Implementación de tokens de actualización
  2. Estrategias de revocación de tokens JWT
  3. Prácticas seguras para almacenar tokens
  4. Rotación de claves de firma y gestión de claves
← Volver a Spring Security 6 & JWT Authentication