Jose JWKS Key Rotation Verification
Verify tokens against a rotating JWKS endpoint with jose, pinning allowed algorithms and caching the key set with stale fallback on outages.
Code
import { createRemoteJWKSet, jwtVerify } from 'jose';
const JWKS_URL = 'https://auth.example.com/.well-known/jwks.json';
const JWKS = createRemoteJWKSet(new URL(JWKS_URL), {
cooldownDuration: 30_000,
timeoutDuration: 5000,
});
async function verifyAccessToken(token) {
try {
const { payload, protectedHeader } = await jwtVerify(token, JWKS, {
algorithms: ['ES256', 'RS256'],
issuer: 'https://auth.example.com',
audience: 'api://billing',
clockTolerance: 10,
});
return {
subject: payload.sub,
scope: payload.scope ?? '',
alg: protectedHeader.alg,
};
} catch (err) {
if (err.code === 'ERR_JWKS_NO_MATCHING_KEY') {
// 轮换刚发生:强制刷新密钥集后重试一次
JWKS.reload();
}
throw err;
}
}
const claims = await verifyAccessToken(process.env.SAMPLE_TOKEN ?? 'dummy');
console.log('verified subject:', claims.subject);Report a problem with this exampleOpens a pre-filled issue on GitHub.