0Pricing
Spring Security 6 & JWT Authentication · Урок

Ротация ключей подписи и управление ключами

Узнайте, зачем и как безопасно ротировать ключи подписи JWT, используя идентификаторы ключей (kid), наборы JWK и перекрывающиеся периоды действия, чтобы избежать простоев

«Ротация ключей подписи и управление ключами» — бесплатный урок Spring Security 6 & JWT Authentication на CoddyKit. Это урок 4 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения Spring Security 6 & JWT Authentication, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс Spring Security 6 & JWT Authentication содержит 4 уроков всего.

Части этого урока еще не переведены и отображаются на английском.

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.

Часто задаваемые вопросы

Урок «Ротация ключей подписи и управление ключами» бесплатный?

Да — полный текст урока «Ротация ключей подписи и управление ключами» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Spring Security 6 & JWT Authentication, подпишись на CoddyKit PRO. Курс Spring Security 6 & JWT Authentication содержит 4 уроков всего.

Чему я научусь в уроке «Ротация ключей подписи и управление ключами»?

Узнайте, зачем и как безопасно ротировать ключи подписи JWT, используя идентификаторы ключей (kid), наборы JWK и перекрывающиеся периоды действия, чтобы избежать простоев Ты практикуешь Spring Security 6 & JWT Authentication с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.

Нужен ли мне опыт, чтобы начать Spring Security 6 & JWT Authentication?

Предыдущий опыт не требуется. Spring Security 6 & JWT Authentication на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 4 из 4.

Сколько времени занимает урок «Ротация ключей подписи и управление ключами»?

Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.

Можно ли писать и запускать код в этом уроке Spring Security 6 & JWT Authentication?

Да. Каждый урок Spring Security 6 & JWT Authentication включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.

Все уроки этого курса

  1. Реализация токенов обновления
  2. Стратегии отзыва токенов JWT
  3. Безопасное хранение токенов
  4. Ротация ключей подписи и управление ключами
← Назад к Spring Security 6 & JWT Authentication