JWT verification with cached JWKS (handles key rotation)

10075
0

JWT auth is easy to get subtly wrong, especially around key rotation. Instead of hard-coding public keys, I fetch JWKS and cache it with a refresh interval so new signing keys are accepted quickly. I still validate iss and aud so tokens from other environments can't be replayed. The middleware stores the sub claim in context and keeps error messages intentionally bland (unauthorized) to avoid leaking details. One operational tip: refresh timeouts should be short so a slow IdP doesn't block requests, and refresh failures should leave the last good keyset in place. With this setup, rotations become boring and you avoid the "midnight auth outage" pattern.