OAuth2 & OIDC for Engineers
OAuth2 is authorization (access tokens); OIDC is authentication (ID tokens) layered on top. Use Authorization Code + PKCE for everything user-facing; client credentials for service-to-service.
Deep dive
Flows that matter today
- Auth Code + PKCE: SPAs, mobile, web — always.
- Client Credentials: machine-to-machine. Scope tokens narrowly.
- Device Code: TVs, CLIs.
- Implicit / Password flows: deprecated. If a vendor still suggests them, push back.
Token types
- Access token: short-lived (5–60 min), bearer, sent to APIs. JWT or opaque.
- Refresh token: longer-lived, exchanged at the auth server for a new access token. Rotate on every use.
- ID token: OIDC only. About the user, not for API auth. Don't send it to your backend as auth.
Validation
Verify signature (JWKS), iss, aud, exp, and nbf. Cache JWKS but respect rotation. For high-value APIs, validate scopes per endpoint.
Real-world example
From productionA team built an internal API that accepted ID tokens as auth — convenient because the frontend had them. An audit found the ID token never expires from the API's view (no exp check, no aud check). A leaked token from one user gave attackers indefinite API access. Fix: switched to access tokens with aud validation; ID tokens stayed client-side.
Interview questions
2 senior-levelQ1OAuth2 vs OIDC — what's the difference?▾
OAuth2 is an authorization framework — it gives apps access tokens to call APIs on a user's behalf. OIDC is an identity layer on top — it adds an ID token containing claims about who the user is. APIs validate access tokens; clients consume ID tokens.
Q2Why is PKCE required for public clients?▾
Public clients (SPAs, mobile) can't keep a client secret. PKCE binds the auth code to a per-request verifier the attacker can't know, preventing code-interception attacks. It's now recommended even for confidential clients.
Common mistakes
Using ID tokens for API authorization.
Skipping
audvalidation.Storing tokens in localStorage and underestimating XSS risk.
Trade-offs
Opaque tokens give central revocation but require an introspection call per request.
JWTs scale better but are hard to revoke before expiry — keep them short-lived.