StackPractices
advanced By Mathias Paulenko

OAuth2 and OIDC: Authorization Code, PKCE, Token Validation

Implement OAuth2 and OIDC in production: PKCE authorization code flow, JWKS token validation, refresh token rotation, revocation, and secure token storage.

Introduction

A stolen access token and an unchecked aud claim sit behind a good share of real API breaches. They’re boring bugs — the kind that pass review because the happy path works. OAuth2 decides what a client may do; OpenID Connect (OIDC) adds who the user is. In production both fail quietly: tokens stored where any injected script can read them, refresh tokens that live forever, signatures nobody verifies.

This guide is for backend and full-stack engineers wiring OAuth2/OIDC into production APIs, SPAs, and services. It covers the authorization code flow with PKCE, token validation against JWKS, refresh token rotation, scope enforcement, client credentials for service-to-service calls, and the revocation and storage decisions most tutorials skip. For the bigger picture — sessions, SAML, passkeys, MFA — see the Complete Guide to Authentication Patterns.

Choosing an OAuth2 Flow

Most OAuth2 incidents start before any code: someone picks a grant type that doesn’t match the client. Choose by who owns the client and where it runs:

Your clientFlowWhy
SPA or mobile app (public client)Authorization Code + PKCENo secret to steal; the PKCE verifier never leaves the device
Server-rendered web app (confidential client)Authorization Code + PKCE + client secretSame flow, plus a real client_secret on the back-channel exchange
Service-to-service, no user involvedClient CredentialsThe token belongs to the service; no redirect, no user context
TVs, consoles, input-constrained devicesDevice Authorization GrantThe user authorizes on a second device with a browser
Renewing access without re-loginRefresh Token grantA call to the token endpoint, not a standalone flow

Two flows to skip in new builds, per the OAuth 2.0 Security Best Current Practice (RFC 9700):

  • Implicit (response_type=token) returns tokens in the URL fragment — they leak into browser history, referer headers, and server logs. Deprecated; use Authorization Code + PKCE even for a pure SPA.
  • Resource Owner Password Credentials (ROPC) hands the user’s password to the client. Acceptable only as a bridge during a legacy migration, and even then treat it as debt.

OAuth2 is also the wrong tool sometimes. If nothing third-party ever calls your API, plain session cookies are simpler. If services authenticate each other with mTLS, you don’t need tokens on the wire at all. And if you only need identity — who the user is — that’s OIDC’s id_token, not OAuth2 by itself.

OAuth2 Roles

flowchart diagram: RO[
  • Resource Owner: the user who owns the data and approves — or denies — access.
  • Client: the application asking for access. Public clients (SPAs, mobile) can’t hold a secret safely; confidential clients (server-side) can.
  • Authorization Server: authenticates the user, captures consent, and issues tokens — Auth0, Keycloak, Entra ID, Cognito.
  • Resource Server: your API. It validates the token and enforces scopes on every request — it never re-asks “who are you”.

Authorization Code Flow with PKCE

PKCE (Proof Key for Code Exchange, RFC 7636) binds the authorization request to the token exchange: the client sends a hash up front and proves it holds the original secret when redeeming the code. An intercepted code is worthless without the verifier. RFC 9700 makes PKCE mandatory for public clients and recommends it for confidential ones too — it also blunts code-injection and login CSRF attacks.

If your client is a browser SPA, the OAuth2 PKCE recipe covers this same flow plus the BFF variant and silent refresh.

Step 1: Generate PKCE verifier and challenge

The verifier is a random 43-character string; the challenge is its SHA-256 hash, base64url-encoded. Anyone who steals the challenge still can’t redeem a code.

// auth/pkce.ts — Generate PKCE pair
import crypto from 'crypto';

function base64UrlEncode(buffer: Buffer): string {
  return buffer.toString('base64')
    .replace(/\+/g, '-')
    .replace(/\//g, '_')
    .replace(/=/g, '');
}

export function generatePkcePair(): { verifier: string; challenge: string } {
  const verifier = base64UrlEncode(crypto.randomBytes(32));
  const challenge = base64UrlEncode(
    crypto.createHash('sha256').update(verifier).digest(),
  );
  return { verifier, challenge };
}

Step 2: Redirect user to authorization endpoint

Two details that bite in production: read credentials through a fail-fast helper so a missing env var explodes at startup instead of producing client_id=undefined, and ask for the offline_access scope if your IdP requires it to issue refresh tokens (Auth0 does; Keycloak returns them by default).

// auth/env.ts — Fail fast on missing configuration
export function env(name: string): string {
  const value = process.env[name];
  if (!value) throw new Error(`Missing env var ${name}`);
  return value;
}
// auth/authorize.ts — Build authorization URL
export function buildAuthUrl(params: {
  authorizationEndpoint: string;
  clientId: string;
  redirectUri: string;
  scope: string;
  state: string;
  codeChallenge: string;
}): string {
  const url = new URL(params.authorizationEndpoint);
  url.searchParams.set('response_type', 'code');
  url.searchParams.set('client_id', params.clientId);
  url.searchParams.set('redirect_uri', params.redirectUri);
  url.searchParams.set('scope', params.scope);
  url.searchParams.set('state', params.state);
  url.searchParams.set('code_challenge', params.codeChallenge);
  url.searchParams.set('code_challenge_method', 'S256');
  return url.toString();
}

// Usage
const { verifier, challenge } = generatePkcePair();
const state = crypto.randomUUID();

// Store verifier and state in the session — they must survive the redirect
session.pkceVerifier = verifier;
session.oauthState = state;

const authUrl = buildAuthUrl({
  authorizationEndpoint: 'https://auth.example.com/authorize',
  clientId: env('OAUTH_CLIENT_ID'),
  redirectUri: 'https://app.example.com/callback',
  // offline_access asks the IdP for a refresh token — required by Auth0, optional elsewhere
  scope: 'openid profile email read:orders offline_access',
  state,
  codeChallenge: challenge,
});

res.redirect(authUrl);

Step 3: Handle callback and exchange code for tokens

Compare state with a constant-time check — a naive !== comparison leaks timing information, which is a small but real signal in an auth endpoint. And once the exchange succeeds, drop the verifier from the session so it can’t be replayed.

// auth/callback.ts — Exchange authorization code for tokens
import { timingSafeEqual } from 'crypto';

app.get('/callback', async (req, res) => {
  const { code, state } = req.query;

  // Constant-time state validation to prevent CSRF
  const expected = Buffer.from(session.oauthState ?? '', 'utf8');
  const received = Buffer.from(String(state ?? ''), 'utf8');
  if (expected.length !== received.length || !timingSafeEqual(expected, received)) {
    return res.status(400).send('Invalid state parameter');
  }

  const tokenResponse = await fetch('https://auth.example.com/oauth/token', {
    method: 'POST',
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
    body: new URLSearchParams({
      grant_type: 'authorization_code',
      client_id: env('OAUTH_CLIENT_ID'),
      client_secret: env('OAUTH_CLIENT_SECRET'), // omit for public clients
      code: String(code),
      redirect_uri: 'https://app.example.com/callback',
      code_verifier: session.pkceVerifier,
    }),
  });

  if (!tokenResponse.ok) {
    // Typical causes: redirect_uri mismatch, reused code, expired code (~30-60s TTL)
    return res.status(400).send('Token exchange failed');
  }

  const tokens = await tokenResponse.json();

  session.accessToken = tokens.access_token;
  session.idToken = tokens.id_token;
  session.refreshToken = tokens.refresh_token;
  session.expiresAt = Date.now() + tokens.expires_in * 1000;
  delete session.pkceVerifier; // single-use: discard after a successful exchange

  res.redirect('/dashboard');
});

Token Response

{
  "access_token": "eyJhbGciOiJSUzI1NiIs...",
  "token_type": "Bearer",
  "expires_in": 3600,
  "refresh_token": "dGhpcyBpcyBhIHJlZnJl...",
  "id_token": "eyJhbGciOiJSUzI1NiIs...",
  "scope": "openid profile email read:orders offline_access"
}

Each field carries more weight than you’d think:

FieldMeaningWatch out
access_tokenThe credential the API accepts — opaque string or JWTBearer means “whoever holds it can use it” — treat it like a password
token_typeHow to present it in the Authorization headerAlmost always Bearer; DPoP/mTLS sender-constrained variants exist
expires_inSeconds until the access token diesKeep it short (5-60 min) and refresh before expiry — see the 60s buffer below
refresh_tokenRenews access without re-loginOnly issued if you asked for it (e.g. offline_access or IdP policy); rotates on each use in modern IdPs
id_tokenOIDC identity JWT with user claimsFor the client only — never forward it to an API
scopeScopes actually grantedMay be narrower than requested; check before assuming write:orders came through

Validating Tokens in Production

Verify access token

Your API should verify the signature against the IdP’s JWKS endpoint — never trust a JWT you didn’t validate, and never hardcode keys, because they rotate. jsonwebtoken already rejects expired tokens by default (exp, nbf), so a manual expiry check on top is dead code. The one knob worth knowing is clockTolerance: if clients skew a few seconds, allow a small window rather than rejecting valid tokens.

// auth/jwt.ts — Validate JWT access tokens against JWKS
import jwt from 'jsonwebtoken';
import jwksClient from 'jwks-rsa';

const client = jwksClient({
  jwksUri: 'https://auth.example.com/.well-known/jwks.json',
  cache: true,
  cacheMaxAge: 600000, // 10 min — short enough for key rotation, long enough to avoid hammering the JWKS endpoint
});

function getKey(header: jwt.JwtHeader, callback: jwt.SigningKeyCallback) {
  client.getSigningKey(header.kid, (err, key) => {
    if (err) return callback(err);
    callback(null, key.getPublicKey());
  });
}

export function verifyAccessToken(token: string): Promise<JwtPayload> {
  return new Promise((resolve, reject) => {
    jwt.verify(token, getKey, {
      algorithms: ['RS256'],
      audience: 'my-api',
      issuer: 'https://auth.example.com/',
      clockTolerance: 30, // tolerate up to 30s of client clock skew on exp/nbf
    }, (err, decoded) => {
      if (err) return reject(err);
      resolve(decoded as JwtPayload);
    });
  });
}

// Middleware — authenticate every request, then inject identity
async function authMiddleware(req: Request, res: Response, next: NextFunction) {
  const authHeader = req.headers.authorization;
  if (!authHeader?.startsWith('Bearer ')) {
    return res.status(401).json({ error: 'Missing bearer token' });
  }

  const token = authHeader.split(' ')[1];

  try {
    const payload = await verifyAccessToken(token);

    // jwt.verify already enforced signature, exp, nbf, iss, aud
    req.user = {
      id: payload.sub,
      scopes: payload.scope?.split(' ') || [],
      email: payload.email,
    };

    next();
  } catch (error) {
    return res.status(401).json({ error: 'Invalid token' });
  }
}

A trade-off worth knowing about the JWKS cache: set it too long and a key rotation makes you reject valid tokens until the cache expires; too short and you hammer the IdP’s endpoint on every cold start. Ten minutes is the common sweet spot — most IdPs overlap old and new keys during rotation anyway.

Validate ID token (OIDC)

The ID token is for the client — it answers “who logged in.” The jsonwebtoken API needs the async form whenever getKey is a function; the synchronous jwt.verify throws when given a callback resolver. Beyond the standard signature checks, verify nonce to close replay attacks and require the OIDC claims that make the token meaningful.

// auth/oidc.ts — Validate OIDC ID token
export function verifyIdToken(idToken: string, expectedNonce: string): Promise<OidcPayload> {
  return new Promise((resolve, reject) => {
    jwt.verify(idToken, getKey, {
      algorithms: ['RS256'],
      audience: env('OAUTH_CLIENT_ID'), // aud must be your client_id
      issuer: 'https://auth.example.com/',
    }, (err, decoded) => {
      if (err) return reject(err);

      const payload = decoded as OidcPayload;

      // Verify nonce to prevent replay attacks
      if (payload.nonce !== expectedNonce) {
        return reject(new Error('Nonce mismatch — possible replay attack'));
      }

      // Verify required OIDC claims (OIDC Core §2)
      if (!payload.sub) return reject(new Error('Missing sub claim'));
      if (!payload.iss) return reject(new Error('Missing iss claim'));
      if (!payload.aud) return reject(new Error('Missing aud claim'));
      if (!payload.exp) return reject(new Error('Missing exp claim'));
      if (!payload.iat) return reject(new Error('Missing iat claim'));

      resolve(payload);
    });
  });
}

Refresh Tokens and Rotation

Refresh tokens are how sessions survive short-lived access tokens — and they’re also the most valuable thing an attacker can steal. Two defenses matter:

  • Rotation: every refresh returns a new refresh token and invalidates the old one. If an old token shows up again, that’s replay.
  • Reuse detection: when an invalidated refresh token gets used, assume theft and revoke the whole token family — force the user to log in again. Auth0, Keycloak, and Entra implement this when rotation is enabled; if you run your own authorization server, it’s on you.
// auth/refresh.ts — Refresh access tokens (with rotation)
export async function refreshAccessToken(refreshToken: string): Promise<TokenResponse> {
  const response = await fetch('https://auth.example.com/oauth/token', {
    method: 'POST',
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
    body: new URLSearchParams({
      grant_type: 'refresh_token',
      client_id: env('OAUTH_CLIENT_ID'),
      client_secret: env('OAUTH_CLIENT_SECRET'),
      refresh_token: refreshToken,
    }),
  });

  if (!response.ok) {
    const error = await response.json();
    // invalid_grant here usually means the refresh token was rotated or revoked — don't retry in a loop
    throw new Error(`Refresh failed: ${error.error_description ?? error.error}`);
  }

  return response.json();
}

// Auto-refresh middleware — renew 60s before expiry, always store the rotated token
async function ensureValidToken(req: Request, res: Response, next: NextFunction) {
  if (Date.now() >= session.expiresAt - 60000) {
    try {
      const tokens = await refreshAccessToken(session.refreshToken);
      session.accessToken = tokens.access_token;
      session.expiresAt = Date.now() + tokens.expires_in * 1000;
      if (tokens.refresh_token) {
        session.refreshToken = tokens.refresh_token; // rotation: replace the old one
      }
    } catch (error) {
      // Don't retry — a failed refresh means the session is dead
      return res.redirect('/login');
    }
  }
  next();
}

Token Storage

Where the refresh token lives decides how bad a stolen-token day gets:

StorageXSS riskCSRF riskWhen it’s the right call
localStorageHigh — any injected script reads itNoneNever for production refresh tokens; tolerable only for short-lived tokens in low-stakes tools
HttpOnly cookie (Secure, SameSite=Lax/Strict)Token unreachable from JSNeeds SameSite plus CSRF protection (double-submit or BFF)Best default for same-site SPAs talking to your own API
BFF — tokens live in a server-side session onlyThe browser never sees tokensStandard session CSRF defensesBest for third-party IdP + SPA; costs you a backend component
OS secure storage (Keychain, Keystore)OS-protectedN/AThe right answer on native mobile apps

The short version: if JavaScript can’t read the token, XSS can’t steal it. That single property is why HttpOnly cookies and BFF dominate serious deployments, and why “store it in localStorage, it’s fine” is the advice that keeps showing up in breach postmortems.

Scope-Based Authorization

AuthN is about identity; scopes decide what you’re allowed to do. Enforce them on the resource server — the client’s own routing doesn’t count, and neither does a claim the IdP merely echoed.

// auth/scopes.ts — Check scopes for API endpoints
function requireScope(scope: string) {
  return (req: Request, res: Response, next: NextFunction) => {
    if (!req.user?.scopes.includes(scope)) {
      // RFC 6750: insufficient_scope is a 403, not a 401 — the token is valid, just not enough
      return res.status(403).json({
        error: 'insufficient_scope',
        required: scope,
      });
    }
    next();
  };
}

// Usage
app.get('/api/orders', authMiddleware, requireScope('read:orders'), getOrders);
app.post('/api/orders', authMiddleware, requireScope('write:orders'), createOrder);
app.delete('/api/orders/:id', authMiddleware, requireScope('delete:orders'), deleteOrder);

One detail removed here that’s worth keeping in mind: don’t echo the caller’s granted scopes back in the error response. It reads as helpful and doubles as a map of what the token can’t do.

OIDC Discovery

Don’t hardcode endpoint URLs. The discovery document at {issuer}/.well-known/openid-configuration (OIDC Discovery spec) publishes everything your client needs — fetch it at startup, cache it, and let the IdP move endpoints underneath you.

// auth/discovery.ts — Fetch OIDC endpoints from the discovery document
export async function getOidcConfig(issuer: string): Promise<OidcConfig> {
  const response = await fetch(`${issuer}/.well-known/openid-configuration`);
  if (!response.ok) throw new Error(`Discovery failed for ${issuer}`);
  return response.json();
}

// Example discovery document (production values from a real IdP)
// {
//   "issuer": "https://auth.example.com",
//   "authorization_endpoint": "https://auth.example.com/authorize",
//   "token_endpoint": "https://auth.example.com/oauth/token",
//   "userinfo_endpoint": "https://auth.example.com/userinfo",
//   "jwks_uri": "https://auth.example.com/.well-known/jwks.json",
//   "end_session_endpoint": "https://auth.example.com/logout",
//   "revocation_endpoint": "https://auth.example.com/oauth/revoke",
//   "introspection_endpoint": "https://auth.example.com/oauth/introspect",
//   "pushed_authorization_request_endpoint": "https://auth.example.com/par",
//   "scopes_supported": ["openid", "profile", "email", "offline_access"],
//   "response_types_supported": ["code"],
//   "grant_types_supported": ["authorization_code", "refresh_token", "client_credentials", "urn:ietf:params:oauth:grant-type:device_code"],
//   "subject_types_supported": ["public"],
//   "id_token_signing_alg_values_supported": ["RS256"],
//   "token_endpoint_auth_methods_supported": ["client_secret_basic", "private_key_jwt"]
// }

If a real IdP’s document still lists token or id_token in response_types_supported, that’s it advertising legacy implicit support — you don’t have to use it.

Client Credentials Flow (Server-to-Server)

This is the only grant with no human in the loop: a service authenticates as itself and gets a token scoped to the service. Two consequences worth internalizing — there’s no user context (don’t try to map the token to a person) and usually no refresh token either (just get a new one when it expires).

// auth/clientCredentials.ts — Machine-to-machine authentication
export async function getClientCredentialsToken(
  clientId: string,
  clientSecret: string,
  scope: string,
): Promise<TokenResponse> {
  const response = await fetch('https://auth.example.com/oauth/token', {
    method: 'POST',
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
    body: new URLSearchParams({
      grant_type: 'client_credentials',
      client_id: clientId,
      client_secret: clientSecret,
      scope,
    }),
  });

  if (!response.ok) throw new Error('Client credentials grant failed');
  return response.json();
}

// Usage: service-to-service calls — prefer private_key_jwt over a shared secret when the IdP supports it
const token = await getClientCredentialsToken(
  env('M2M_CLIENT_ID'),
  env('M2M_CLIENT_SECRET'),
  'read:orders write:orders',
);

const orders = await fetch('https://api.example.com/orders', {
  headers: { Authorization: `Bearer ${token.access_token}` },
});

Token Revocation and Logout

“Log out” in OAuth2-land is three operations, not one: drop the local session, revoke the tokens at the authorization server (RFC 7009), and end the IdP session so SSO doesn’t silently log the user back in.

// auth/revoke.ts — Revoke a token at the authorization server (RFC 7009)
export async function revokeToken(
  token: string,
  hint: 'access_token' | 'refresh_token',
): Promise<void> {
  await fetch('https://auth.example.com/oauth/revoke', {
    method: 'POST',
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
    body: new URLSearchParams({
      token,
      token_type_hint: hint,
      client_id: env('OAUTH_CLIENT_ID'),
      client_secret: env('OAUTH_CLIENT_SECRET'),
    }),
  });
  // RFC 7009: the endpoint returns 200 even for unknown/invalid tokens — don't branch on the result
}

If your resource server consumes opaque tokens, it also needs introspection (RFC 7662) — a call that asks the authorization server whether a token is still active and what it grants:

// auth/introspect.ts — Ask the AS whether a token is active (RFC 7662)
export async function introspectToken(token: string): Promise<boolean> {
  const response = await fetch('https://auth.example.com/oauth/introspect', {
    method: 'POST',
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
    body: new URLSearchParams({
      token,
      client_id: env('OAUTH_CLIENT_ID'),
      client_secret: env('OAUTH_CLIENT_SECRET'),
    }),
  });
  const data = await response.json();
  return data.active === true; // cache briefly — introspecting every request adds latency
}

For logout, redirect the browser to the end_session_endpoint from the discovery document with an id_token_hint and a registered post_logout_redirect_uri. Clear your local session first, revoke the refresh token, then send the user through the IdP logout — order matters, because an active IdP session will hand you a fresh SSO login on the next redirect.

Production Hardening

The mechanisms above are the baseline every IdP supports. The next layer is what separates a tutorial from a hardened deployment:

  • PAR — Pushed Authorization Requests (RFC 9126): the client POSTs the authorization request to the token endpoint first and gets back a request_uri; the browser then carries only a reference. Parameters stay out of URLs, logs, and referer headers — worth it for sensitive scopes.
  • DPoP (RFC 9449): binds each token to a client-held key; the sender proves possession on every request with a signed DPoP proof. A stolen DPoP token is useless without the private key — the practical fix for token exfiltration.
  • mTLS sender-constrained tokens (RFC 8705): the certificate-bound alternative to DPoP, common in open banking and regulated stacks.
  • private_key_jwt client authentication: the confidential client signs a JWT with its private key instead of sending a shared client_secret — nothing reusable crosses the wire.
  • Short-lived access tokens: 5-60 minutes depending on risk. Longer lifetimes are a real choice in low-risk internal traffic — not a default.

Best Practices

  • Always use PKCE — public clients must, confidential clients should. It costs three lines and removes an entire attack class.
  • Verify signatures, iss, aud, exp, and nonce on every token — against JWKS, not hardcoded keys. A token minted for your staging API will otherwise open production, and I’ve seen exactly that misconfiguration ship.
  • Rotate refresh tokens and treat reuse as compromise — revoke the whole token family, not just the replayed token.
  • Keep access tokens short-lived and revoke refresh tokens on logout, password change, or admin action.
  • Store tokens where JavaScript can’t reach — HttpOnly cookies or a BFF session for web, OS secure storage for mobile.
  • Validate state constant-time and nonce on the ID token — CSRF and replay are cheap to prevent and embarrassing to explain.
  • Enforce scopes server-side on every request, and return insufficient_scope without leaking the caller’s granted set.
  • Fetch endpoints from the discovery document — hardcoded URLs break the first time the IdP renames an endpoint.
  • Prefer PAR and private_key_jwt for confidential clients in regulated or high-risk traffic.
  • Use the end_session_endpoint on logout, after revoking tokens — or SSO logs the user straight back in.

For a checklist version of these decisions applied to API design, see the API Authentication Design Template.

Common Mistakes

  • Storing tokens in localStorage: any XSS payload reads them silently. Use HttpOnly cookies or a BFF so there’s nothing for the script to steal.
  • Skipping PKCE on a SPA: an intercepted authorization code is redeemable by whoever has it. PKCE makes it useless without the verifier.
  • Not validating the signature: an attacker can mint a JWT that decodes perfectly. Verify against JWKS — decoding isn’t validating.
  • Checking exp but not aud: a token issued for a different API or a different client_id still parses and still isn’t expired. aud is the check people forget.
  • Long-lived access tokens: a stolen one stays valid for its full TTL. Short TTLs plus refresh rotation cap the damage window.
  • Missing state validation: an attacker can complete their login flow inside your session and attach their account to your browser. Constant-time state checks kill this.
  • Retrying failed refreshes in a loop: invalid_grant on refresh usually means the token was rotated or revoked — looping just hammers the token endpoint and can trip rate limits. Redirect to login instead.

See Also

Further Reading

Frequently Asked Questions

What is the difference between OAuth2 and OIDC?

OAuth2 is an authorization framework — it answers "what may this client do" (scopes, access tokens). OIDC is an authentication layer on top — it answers "who is this user" (ID token, userinfo endpoint). Every OIDC deployment includes OAuth2; plenty of OAuth2 deployments have no OIDC at all.

What is PKCE and why is it required?

PKCE (RFC 7636) adds a cryptographic challenge to the authorization code flow. The client generates a random verifier, sends its SHA-256 hash with the authorization request, and proves it holds the verifier when exchanging the code. An intercepted code can't be redeemed without the verifier — required for public clients, recommended everywhere.

What is the difference between access token and ID token?

Access tokens authorize API calls — opaque or JWT, sent to the resource server. ID tokens carry identity claims (sub, email, name) as a JWT for the client only. Sending an ID token to an API is a common bug: the API needs scopes, not your name.

When should I use client credentials flow?

For server-to-server calls with no user involved: cron jobs, internal services, partner APIs. The client authenticates with its own credentials and gets a service-scoped token — no user context, no refresh token.

Where should I store tokens in a SPA?

Not localStorage — any XSS reads it. HttpOnly cookies with SameSite for same-site setups, or the BFF pattern where tokens never leave the server, for third-party IdPs. Mobile apps use OS secure storage.

Is the implicit flow still OK for SPAs?

No — RFC 9700 deprecates it. Tokens in the URL fragment leak through browser history and referer headers. Authorization Code + PKCE is the replacement for every browser-based client.

How do I handle token revocation?

POST to the revocation endpoint (RFC 7009) with the token, a token_type_hint, and client credentials — for refresh token rotation, the old token is revoked when the new one is issued. On logout, revoke first, then redirect through end_session_endpoint so the IdP session closes too.