Security8 min read

OAuth 2.0 & OpenID Connect

Implement OAuth 2.0 authorization flows and OIDC authentication correctly using PKCE, state parameters, and token validation.

oauth2oidcauthenticationauthorization

OAuth 2.0 is the industry standard for delegated authorization. OpenID Connect (OIDC) builds on OAuth 2.0 to add authentication via ID tokens. Correct implementation prevents token theft, CSRF, and authorization bypass.

Use authorization code flow with PKCE for all public clients (SPAs, mobile apps). Use client credentials for machine-to-machine. Validate every token server-side. Never implement OAuth from scratch-use certified libraries.

Workflow

  1. Choose the correct grant typeWrong grant type exposes tokens in URLs, logs, or to unauthorized parties.
  2. Implement PKCE for public clientsPKCE prevents authorization code interception by malicious apps on the same device.
  3. Validate state and nonce parametersState prevents CSRF; nonce prevents replay attacks on ID tokens.
  4. Validate tokens correctlyAccepting unvalidated tokens is equivalent to having no auth at all.
  5. Handle token storage and refresh securelyTokens stored in localStorage are accessible to XSS; improper refresh exposes refresh tokens.

Output Format

Authorization code + PKCE flow implemented, state/nonce validated, tokens validated against JWKS, refresh rotation enabled, httpOnly cookie storage.

Examples

PKCE verifier: `const verifier = crypto.randomBytes(32).toString("base64url"); const challenge = crypto.createHash("sha256").update(verifier).digest("base64url")`
JWT validation: `import { jwtVerify, createRemoteJWKSet } from "jose"; const JWKS = createRemoteJWKSet(new URL(provider + "/.well-known/jwks.json")); const { payload } = await jwtVerify(token, JWKS, { issuer: provider, audience: clientId })`
State check: `if (req.query.state !== req.session.oauthState) return res.status(403).send("CSRF detected")`

Edge Cases & Gotchas

  • Open redirect in redirect_uri: strictly whitelist allowed URIs in provider settings
  • Token substitution: verify aud claim matches your client_id, not just any valid token
  • Clock skew: allow 5min leeway on iat/exp validation to handle server clock differences

When to Break These Rules

  • For internal-only services where all clients are trusted and OAuth complexity adds no value, use simpler API key or mTLS authentication.

Reference Files

  • RFC 6749 OAuth 2.0: https://datatracker.ietf.org/doc/html/rfc6749
  • RFC 7636 PKCE: https://datatracker.ietf.org/doc/html/rfc7636
  • OIDC Core spec: https://openid.net/specs/openid-connect-core-1_0.html
  • OAuth Security BCP: https://datatracker.ietf.org/doc/html/draft-ietf-oauth-security-topics

More skills in this library

Browse all technical skills - Mobile, AI/ML, Web, Backend, Design, and Product.