Rotação de chaves de assinatura e gerenciamento de chaves
Aprenda por que e como rotacionar chaves de assinatura de JWT com segurança, usando identificadores de chave (kid), conjuntos JWK e validade sobreposta para evitar indisponibilidade.
Rotação de chaves de assinatura e gerenciamento de chaves é uma aula grátis de Spring Security 6 & JWT Authentication no CoddyKit. Esta é a aula 4 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de Spring Security 6 & JWT Authentication, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de Spring Security 6 & JWT Authentication inclui 4 aulas no total.
Partes desta aula ainda não foram traduzidas e aparecem em 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
kidheaders 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.
Perguntas Frequentes
A aula “Rotação de chaves de assinatura e gerenciamento de chaves” é grátis?
Sim — o texto completo de “Rotação de chaves de assinatura e gerenciamento de chaves” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de Spring Security 6 & JWT Authentication, atualize para CoddyKit PRO. O curso de Spring Security 6 & JWT Authentication inclui 4 aulas no total.
O que vou aprender em “Rotação de chaves de assinatura e gerenciamento de chaves”?
Aprenda por que e como rotacionar chaves de assinatura de JWT com segurança, usando identificadores de chave (kid), conjuntos JWK e validade sobreposta para evitar indisponibilidade. Você pratica Spring Security 6 & JWT Authentication com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.
Preciso ter experiência prévia para começar Spring Security 6 & JWT Authentication?
Nenhuma experiência prévia é necessária. Spring Security 6 & JWT Authentication no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 4 de 4.
Quanto tempo leva a aula “Rotação de chaves de assinatura e gerenciamento de chaves”?
A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.
Posso escrever e executar código nesta aula de Spring Security 6 & JWT Authentication?
Sim. Cada aula de Spring Security 6 & JWT Authentication inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.
Todas as aulas deste curso
- Implementação de tokens de atualização
- Estratégias de revogação de tokens JWT
- Práticas seguras de armazenamento de tokens
- Rotação de chaves de assinatura e gerenciamento de chaves