Full answer
OIDC basics
- Same flows as OAuth (use the code flow with PKCE) with the scope openid. The token response adds an id_token. A /userinfo endpoint returns more claims, and a discovery document (/.well-known/openid-configuration) lists endpoints and the jwks_uri.
- ID token claims: iss (who issued), sub (stable user id, unique per issuer), aud (client id), exp, iat, nonce, and optional profile claims (email, name).
Validation checklist
- Parse the header. Accept only the algorithm you expect (RS256 or ES256 as published by the provider). Never trust alg from the token, and reject none. This blocks algorithm confusion attacks (a token signed with HS256 using the public key as the secret).
- Find the key by kid in the provider's JWKS (cache it, refresh on unknown kid), and verify the signature.
- iss equals the issuer you configured, exactly.
- aud contains your client id.
- exp is in the future (allow a small clock skew), and iat is sensible.
- nonce equals the value you stored in the session at the start of the login (prevents replay of a token from another login).
- Identify users by the pair (iss, sub), not by email.
Access tokens may be opaque. Do not parse them in the client unless the provider documents their format.
const crypto = require('node:crypto');
const { publicKey, privateKey } = crypto.generateKeyPairSync('rsa', { modulusLength: 2048 });
const b64 = (o) => Buffer.from(JSON.stringify(o)).toString('base64url');
function issue(claims, header = { alg: 'RS256', typ: 'JWT', kid: 'key-1' }, key = privateKey) {
const body = `${b64(header)}.${b64(claims)}`;
const sig = header.alg === 'RS256' ? crypto.sign('sha256', Buffer.from(body), key) : crypto.createHmac('sha256', publicKey.export({ type: 'spki', format: 'pem' })).update(body).digest();
return `${body}.${sig.toString('base64url')}`;
}
function validateIdToken(token, { issuer, clientId, nonce, now }) {
const [h, p, s] = token.split('.');
const header = JSON.parse(Buffer.from(h, 'base64url')), claims = JSON.parse(Buffer.from(p, 'base64url'));
if (header.alg !== 'RS256') return 'rejected: unexpected alg ' + header.alg; // pinned algorithm
if (!crypto.verify('sha256', Buffer.from(`${h}.${p}`), publicKey, Buffer.from(s, 'base64url'))) return 'rejected: bad signature';
if (claims.iss !== issuer) return 'rejected: wrong issuer';
if (![].concat(claims.aud).includes(clientId)) return 'rejected: wrong audience';
if (claims.exp <= now - 60) return 'rejected: expired';
if (claims.nonce !== nonce) return 'rejected: nonce mismatch';
return `accepted: user key = ${claims.iss}|${claims.sub}`;
}
const now = 1_800_000_000;
const ctx = { issuer: 'https://id.example.com', clientId: 'my-client', nonce: 'n-123', now };
const good = { iss: ctx.issuer, sub: 'u-42', aud: 'my-client', exp: now + 600, iat: now, nonce: 'n-123' };
console.log('valid token :', validateIdToken(issue(good), ctx));
console.log('wrong audience :', validateIdToken(issue({ ...good, aud: 'other-app' }), ctx));
console.log('wrong issuer :', validateIdToken(issue({ ...good, iss: 'https://evil.example' }), ctx));
console.log('expired :', validateIdToken(issue({ ...good, exp: now - 3600 }), ctx));
console.log('nonce replay :', validateIdToken(issue({ ...good, nonce: 'old' }), ctx));
console.log('tampered claims :', validateIdToken(issue(good).replace(/\.[^.]+\./, '.' + b64({ ...good, sub: 'admin' }) + '.'), ctx));
console.log('alg confusion :', validateIdToken(issue(good, { alg: 'HS256', typ: 'JWT' }), ctx));A fresh RSA key pair is generated for each run, so only the results are printed, never the tokens. Real clients fetch the public key from the provider's JWKS and use a maintained library such as jose. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, run once): valid token : accepted: user key = https://id.example.com|u-42 wrong audience : rejected: wrong audience wrong issuer : rejected: wrong issuer expired : rejected: expired nonce replay : rejected: nonce mismatch tampered claims : rejected: bad signature alg confusion : rejected: unexpected alg HS256
Key points
- OIDC adds identity (an ID token) on top of OAuth 2.0.
- The ID token is for the client; the access token is for APIs.
- Check signature, algorithm, iss, aud, exp and nonce.
- Pin the expected algorithm and fetch keys from the JWKS.
- Use (iss, sub) as the user key.
Common mistakes
- Using an ID token to call an API.
- Not checking aud, so a token for another app is accepted.
- Trusting the alg field from the token header.
- Identifying users by email address.
- Skipping nonce checks.
Follow-ups
- What is a JWKS and how do you handle key rotation?
- What is the difference between the UserInfo endpoint and ID token claims?
- What does at_hash protect?
Tips
- Contrast authentication with authorization.
- List the checks quickly.
- Mention algorithm pinning.