JWT Key Rotation & kid Handling
On this page
Key Rotation Is Inevitable
Signing keys will rotate: - routine security policy - key compromise - certificate expiration - identity provider changes If your service cannot handle key rotation smoothly, you will get: - sudden 401 spikes - full production outages - emergency config hacks that weaken security Production rule: Your service must accept multiple valid signing keys during transition, and reject everything else.Real Production Incident
Symptoms: - All authenticated requests start failing with 401 at once. - No code deployment happened. - Identity provider rotated signing key. - Service only trusted a single hardcoded key. Root cause: - No support for multiple keys. - No automatic metadata refresh. - Key rotation not tested in staging. This is not an auth bug. It is an operational failure.Symptom → Cause → Diagnosis → Fix
Symptom: - sudden global 401 failures - valid tokens rejected - logs show signature validation errors Cause: - hardcoded IssuerSigningKey - no metadata endpoint usage - no support for multiple signing keys - no kid handling Diagnosis: - Inspect JWT header for kid. - Compare against configured keys. - Check whether key metadata endpoint changed. - Review TokenValidationParameters for key resolution logic. Fix: - Use signing key resolution via trusted metadata (e.g., OpenID Connect). - Support multiple keys simultaneously. - Refresh metadata periodically. - Monitor signature validation failures by reason.What kid Does
JWT header contains: - alg - kid (key identifier) kid allows the verifier to: - select the correct public key among multiple active keys. Production rule: Do not ignore kid if your issuer rotates keys.Anti-Pattern: Single Hardcoded Key
This breaks during rotation:
options.TokenValidationParameters = new TokenValidationParameters
{
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("hardcoded-secret"))
};
Problems:
- no rotation
- no key rollover window
- secret often stored in config or repo
- impossible zero-downtime rotation
Correct Pattern: Key Discovery and Multiple Keys
For external identity providers: - rely on metadata endpoint (OpenID Connect discovery) - let framework fetch signing keys - validate issuer and audience strictly Conceptually:
options.Authority = "https://issuer.example.com";
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateIssuerSigningKey = true
};
The framework retrieves and caches keys from the issuer’s JWKS endpoint.
Production rule:
Trust keys only from the configured Authority.