How-To Guide

How to Validate OIDC ID Tokens Correctly

Verify an OpenID Connect ID token against the provider JWKS and enforce issuer, audience, nonce and time claims so login cannot be spoofed.

On this page

  1. Introduction
  2. What an ID Token Claims and Why Not to Trust It Raw
  3. Fetching and Caching the JWKS
  4. Verifying Signature, Issuer and Audience
  5. Checking Nonce, auth_time and azp
  6. Handling Key Rotation
  7. Common Validation Failures
  8. Conclusion

Introduction

In OpenID Connect the identity provider returns an ID token, a signed JSON Web Token, as proof that the user authenticated. The token is a credential, and a backend that trusts any well-formed ID token is trivially spoofable: anyone can craft a JWT with your provider’s name in the issuer field. Correct validation checks the signature against the provider’s published keys and then checks every claim that binds the token to your application and to this specific login. This article shows the full check with the jose library, including key rotation, nonce, and the claim pitfalls that turn validation into a false sense of security.

What an ID Token Claims and Why Not to Trust It Raw

An ID token is a compact JWT with three parts: a header naming the signing algorithm and key id, a payload of claims, and a signature. The claims include iss for the issuer, sub for the user’s stable identifier at that issuer, aud for the client the token is issued to, exp and iat for expiry and issue time, and often nonce, auth_time, and azp. Base64 decoding the payload reveals these claims to anyone; decoding proves nothing. Trust comes from verifying the signature with the issuer’s public key and then confirming the claims match your expectations.

The three classic mistakes are trusting the alg header, skipping the audience check, and skipping the issuer check. An attacker can set alg to none or to a symmetric algorithm and sign with your public key as the secret. A token issued for another app is accepted if you do not check aud. A token from a different provider is accepted if you do not check iss. Each of these alone is enough to bypass authentication.

Fetching and Caching the JWKS

The provider publishes its public keys as a JSON Web Key Set at a well-known endpoint. Fetch it once and cache it, keyed by the kid in the token header, and refresh on a cache miss rather than on every request. Never fetch keys per request, because that adds latency and couples your availability to the provider’s JWKS endpoint. The jose library provides createRemoteJWKSet, which handles fetching, caching and kid lookup for you.

import { createRemoteJWKSet, jwtVerify } from 'jose';

const issuer = 'https://accounts.example.com';
// createRemoteJWKSet caches keys and refetches on an unknown kid.
const JWKS = createRemoteJWKSet(
  new URL(issuer + '/.well-known/jwks.json'),
  { cacheMaxAge: 600_000 },   // 10 minutes
);

Verifying Signature, Issuer and Audience

Verification is a single call that pins the algorithms you accept, the expected issuer and the expected audience. Pinning algorithms prevents the alg-confusion attack: even if the header says HS256, jwtVerify will reject it because you only allow RS256 or ES256. The audience must be your client id, and a token with aud set to a different client must fail. The issuer must match exactly, including scheme and trailing path.

async function validateIdToken(idToken, clientId) {
  const { payload, protectedHeader } = await jwtVerify(idToken, JWKS, {
    issuer,
    audience: clientId,
    algorithms: ['RS256', 'ES256'],   // never allow "none" or HMAC
    clockTolerance: 5,                // seconds of skew
  });
  // jwtVerify already enforced exp and nbf.
  return { payload, alg: protectedHeader.alg, kid: protectedHeader.kid };
}

Checking Nonce, auth_time and azp

Signature, issuer and audience are not enough to prove this token belongs to this login flow. The nonce is a value the client generated before redirecting and must match the nonce claim in the returned token; it prevents an attacker from replaying a token captured from another session. If the client sent a max_age or an auth_time requirement, verify the auth_time claim is recent enough to satisfy it.

The azp claim matters when a token has multiple audiences: it records the authorized party, the client that actually requested the token. If azp is present it must equal your client id. Additionally, treat sub together with iss as the user identity key, never sub alone, because a sub is only unique within one issuer. Two different providers can hand out the same sub for different people.

Handling Key Rotation

Providers rotate signing keys. A well-behaved JWKS exposes both the new and the old key during the overlap window, and createRemoteJWKSet refetches when it sees a kid it does not know. If you implement caching yourself, do the same: match by kid, and on a cache miss fetch the JWKS once and retry, rather than failing the request or refetching for every unknown kid. Cache the JWKS for minutes, not seconds.

Some providers also rotate by publishing a new key before signing with it. Do not assume the first key in the set is the current one; always select by kid. If a token’s kid is absent from the set even after a refetch, that is a validation failure, not a reason to fall back to skipping the signature.

Common Validation Failures

The most dangerous failure is disabling signature verification for testing and shipping it. The second is not pinning algorithms. The third is validating the ID token but then authorizing requests with an access token whose signature was never checked, or checking the signature without checking audience, so a token minted for another resource server is accepted. Always verify the access token your API actually consumes, against the audience that names your API.

Do not confuse the ID token and the access token. The ID token is for the client to learn who logged in; the access token is for APIs to authorize. An API that validates ID tokens instead of access tokens will reject legitimate calls and may accept tokens minted for a frontend. Keep the two separate and validate each for its intended consumer.

Conclusion

Validating an OIDC ID token means verifying the signature against the provider’s JWKS with a fixed algorithm allowlist, and then enforcing issuer, audience, nonce and time claims. Cache the JWKS and select keys by kid so rotation is transparent. Never trust the alg header, never skip the audience check, and never treat a base64 payload as proof. Validate the ID token at the client and the access token at your API, each against its own audience, and login becomes genuinely hard to spoof.

Sources: OpenID Connect Core 1.0, RFC 7517: JSON Web Key (JWK), jose library documentation.

FAQ

Why is trusting the alg header dangerous?
An attacker can set alg to none or to a symmetric algorithm and sign the token with your public key as the secret. Pinning the accepted algorithms during verification rejects any token whose header does not match your allowlist, which closes both attacks.
Should my API validate the ID token or the access token?
The access token. The ID token is for the client to learn who authenticated; the API authorizes using the access token, validated against the audience that names your API. Accepting ID tokens at the API accepts the wrong credential.

Related Examples