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);How it works
Count the function verifyAccessToken as the entire surface area of Jose JWKS Key Rotation Verification.
Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed. createRemoteJWKSet, jwtVerify are the only symbols borrowed from jose — the coupling is explicit and narrow.
Configuration comes from the environment — it reads SAMPLE_TOKEN, so the same code switches behavior between environments without edits.
The result comes back as an object carrying sub, alg.
What to watch for
- Plan for an install step:
joseis a real dependency, resolved by the package manager.
Using it
The main signature reads async function verifyAccessToken(token)
Output lines are prefixed (verified subject:), making each step’s effect easy to spot.
The call returns sub, alg — destructure what you need at the call site.
Key statements
const claims = await verifyAccessToken(process.env.SAMPLE_TOKEN ?? 'dummy');
const { payload, protectedHeader } = await jwtVerify(token, JWKS, {
algorithms: ['ES256', 'RS256'],
issuer: 'https://auth.example.com',
audience: 'api://billing',
clockTolerance: 10,
});
Interactive Tools for This Topic
FAQ
- Does `verifyAccessToken` modify its input?
- It does not. Inputs are only read; the return value is freshly built.
- Does this require external packages?
- Yes — `jose`. Add it to your project before running the snippet.
Report a problem with this exampleOpens a pre-filled issue on GitHub.