Skip to content
Derar Sattouf

OAuth 2.1 and OIDC: Common API Security Pitfalls

Updated Security

OAuth 2.1 and OIDC: Common API Security Pitfalls

OAuth and OpenID Connect (OIDC) are the backbone of modern authentication, and also the source of an endless stream of vulnerabilities. Not because the specs are broken, but because they offer many options, and developers pick the wrong ones, skip a validation step, or store a token somewhere unsafe.

OAuth 2.1 consolidates years of security best practice into one document: it effectively mandates Authorization Code flow with PKCE, forbids the implicit and password grants, requires exact redirect URI matching, and tightens refresh token handling.

OAuth is for authorization (delegated access); OIDC adds authentication, meaning who the user is, through the ID token. Never confuse ID tokens (for the client) with access tokens (for APIs).

Use Authorization Code + PKCE for every client: SPAs, mobile and server-rendered apps. Don't use the implicit or password grants. Validate state, nonce, issuer, audience, expiry and signature every time, and pin the accepted algorithms.

Keep tokens out of localStorage. Prefer a backend-for-frontend (BFF) that holds tokens and gives the browser an HttpOnly session cookie. Rotate refresh tokens and detect reuse, and use short-lived access tokens.

Standards evolve. Check the current OAuth 2.1 draft and your identity provider's documentation for exact parameter names and supported features.

Where the standards stand

  • OAuth 2.1 is an IETF specification that consolidates OAuth 2.0 with its security best practices; check the IETF datatracker to see whether it has been published as an RFC yet. Its content is already what you should implement.
  • RFC 9700 (OAuth 2.0 Security Best Current Practice, published in January 2025) is the authoritative list of what to do and avoid today, and it is a stable RFC you can cite.
  • OIDC Core 1.0 remains the identity layer, with extensions for discovery, session management and logout.
  • Related RFCs that come up below: PKCE (RFC 7636), JWT access token profile (RFC 9068), DPoP (RFC 9449), Pushed Authorization Requests (RFC 9126), Resource Indicators (RFC 8707), Authorization Server Issuer Identification (RFC 9207), Token Exchange (RFC 8693), Device Authorization Grant (RFC 8628) and Protected Resource Metadata (RFC 9728).

Roles and vocabulary

TermMeaning
Resource OwnerThe user
ClientYour app requesting access
Authorization Server (AS)Issues tokens (Auth0, Okta, Keycloak, Entra ID, etc.)
Resource Server (RS)Your API that accepts access tokens
Access tokenCredential presented to the API
ID tokenJWT describing the authenticated user, consumed by the client
Refresh tokenLong-lived credential used to get new access tokens
ScopeNamed permission the client requests

A frequent mistake: using the ID token to call your API. The ID token's audience is the client; your API should only accept access tokens issued with the API as the audience.

The correct flow: Authorization Code with PKCE

Browser/App                   Authorization Server               API
    │  1. generate code_verifier, code_challenge=S256(verifier)     │
    │  2. redirect ──> /authorize?response_type=code&client_id=..   │
    │        &redirect_uri=..&scope=openid profile api:read         │
    │        &state=..&nonce=..&code_challenge=..&code_challenge_method=S256
    │  3. user logs in + consents                                   │
    │  4. redirect back with ?code=..&state=..                      │
    │  5. POST /token  code + code_verifier (+ client auth)         │
    │  <── access_token, id_token, refresh_token                    │
    │  6. call API with Authorization: Bearer <access_token> ──────>│

Why PKCE matters

Without PKCE, anyone who intercepts the authorization code (malicious app registered for the same custom URI scheme, browser extension, log file, referrer leak) can exchange it for tokens. PKCE binds the code to a secret only the legitimate client knows (the code_verifier).

Generating PKCE and state in the browser

const b64url = (buf: ArrayBuffer) =>
  btoa(String.fromCharCode(...new Uint8Array(buf)))
    .replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");

export async function createAuthRequest() {
  const verifierBytes = crypto.getRandomValues(new Uint8Array(32));
  const verifier = b64url(verifierBytes.buffer);
  const challenge = b64url(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(verifier)));
  const state = b64url(crypto.getRandomValues(new Uint8Array(16)).buffer);
  const nonce = b64url(crypto.getRandomValues(new Uint8Array(16)).buffer);

  sessionStorage.setItem("oauth", JSON.stringify({ verifier, state, nonce }));

  const url = new URL("https://auth.example.com/authorize");
  url.search = new URLSearchParams({
    response_type: "code",
    client_id: "my-spa",
    redirect_uri: "https://app.example.com/callback",
    scope: "openid profile api:read",
    state, nonce,
    code_challenge: challenge,
    code_challenge_method: "S256",
  }).toString();
  return url.toString();
}

Use a well-tested library (oidc-client-ts, openid-client, Auth.js, your IdP's SDK) in production rather than hand-rolling this, but understand what it does.

Pitfall: weak redirect URI handling

Redirect URI bugs enable authorization-code theft and account takeover.

  • Register exact redirect URIs. No wildcards, no pattern matching, no "starts with."
  • Never accept a redirect_uri from the request that was not pre-registered.
  • Avoid open redirects anywhere on your domain; they can chain into OAuth attacks.
  • For native apps, use claimed HTTPS links or the platform's secure browser APIs, not custom schemes alone.

Pitfall: missing state and nonce checks

  • state protects against CSRF on the callback. Generate it per request, store it, and compare on return. Reject mismatches.
  • nonce is embedded in the ID token and prevents replay. Verify the ID token's nonce equals the one you sent.
export async function handleCallback(params: URLSearchParams) {
  const saved = JSON.parse(sessionStorage.getItem("oauth") ?? "null");
  if (!saved) throw new Error("No pending auth request");
  if (params.get("state") !== saved.state) throw new Error("State mismatch");
  if (params.get("error")) throw new Error(params.get("error_description") ?? "OAuth error");

  const res = 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",
      code: params.get("code")!,
      redirect_uri: "https://app.example.com/callback",
      client_id: "my-spa",
      code_verifier: saved.verifier,
    }),
  });
  if (!res.ok) throw new Error("Token exchange failed");
  sessionStorage.removeItem("oauth");
  return res.json();
}

Pitfall: sloppy JWT validation

Your API must validate every access token it receives. A correct checklist:

  1. Signature verifies against the AS's published keys (JWKS), selected via kid.
  2. Algorithm is pinned (for example RS256 or ES256). Reject alg: none and never let the token choose a different family (HS256 with a public key as the secret is a classic attack).
  3. iss equals your expected issuer exactly.
  4. aud contains your API's identifier.
  5. exp is in the future, nbf (if present) is in the past, with small clock-skew tolerance (30-60 seconds).
  6. Required scopes or roles are present for the requested operation.
import { createRemoteJWKSet, jwtVerify } from "jose";

const JWKS = createRemoteJWKSet(new URL("https://auth.example.com/.well-known/jwks.json"));

export async function verifyAccessToken(token: string) {
  const { payload } = await jwtVerify(token, JWKS, {
    issuer: "https://auth.example.com/",
    audience: "https://api.example.com",
    algorithms: ["RS256"],       // pinned
    clockTolerance: "30s",
  });
  return payload;
}

export const requireScope = (payload: { scope?: string }, needed: string) => {
  if (!(payload.scope ?? "").split(" ").includes(needed)) {
    throw Object.assign(new Error("insufficient_scope"), { status: 403 });
  }
};

For high-risk APIs consider token introspection (RFC 7662) or short lifetimes so revocation takes effect quickly; pure JWT validation cannot know a token was revoked until it expires.

Authorization is more than scopes

Scopes say what the client may do; they do not say whether this user may access this record. Check ownership or policy per resource. Skipping this check is the classic broken object-level authorization (BOLA/IDOR) bug, consistently near the top of API security risk lists.

// WRONG: trusts that any valid token with "orders:read" may read any order
app.get("/orders/:id", auth("orders:read"), async (req, res) => {
  res.json(await db.orders.findById(req.params.id));
});

// RIGHT: scope AND ownership
app.get("/orders/:id", auth("orders:read"), async (req, res) => {
  const order = await db.orders.findOne({ id: req.params.id, userId: req.user.sub });
  if (!order) return res.status(404).end();   // 404 avoids revealing existence
  res.json(order);
});

Pitfall: tokens in the browser

Storing tokens in localStorage exposes them to any XSS. A single injected script can read and exfiltrate them, and the attacker can use them from anywhere.

The server performs the OAuth flow, keeps access and refresh tokens server-side, and gives the browser only an opaque session cookie.

// Next.js / Node BFF sketch
res.cookie("sid", sessionId, {
  httpOnly: true,       // not readable by JS
  secure: true,         // HTTPS only
  sameSite: "lax",      // CSRF defense (use "strict" where flows allow)
  path: "/",
  maxAge: 60 * 60 * 8 * 1000,
});

The browser calls /api/* on your BFF, which attaches the access token and forwards to the real API. This removes tokens from JavaScript entirely, and pairs well with CSRF protection (SameSite cookies plus an anti-CSRF token or custom header for state-changing requests).

If you must keep tokens in memory in a pure SPA, keep them in memory only (not storage), use short lifetimes, and have a strict Content-Security-Policy.

Pitfall: bearer tokens can be stolen and replayed

A bearer token works for whoever holds it. Defenses, from simple to strong:

  1. Short lifetimes and narrow audiences/scopes, so a stolen token is worth little.
  2. Sender-constrained tokens: bind the token to a key the client holds, so a stolen token is useless without the private key.
    • DPoP (RFC 9449) works at the application layer: the client signs a small proof JWT per request, and the token carries a thumbprint of the client's public key.
    • mTLS-bound tokens (RFC 8705) bind to a client certificate; common in financial-grade (FAPI) profiles.
  3. Pushed Authorization Requests (PAR) and signed request objects keep authorization parameters out of the browser URL where they could be tampered with or logged.

A DPoP-bound request looks like this (header values shortened):

POST /orders HTTP/1.1
Host: api.example.com
Authorization: DPoP eyJhbGciOi...access-token...
DPoP: eyJ0eXAiOiJkcG9wK2p3dCIsImFsZyI6IkVTMjU2IiwiandrIjp7...proof-jwt...

The API must verify the proof's signature, the HTTP method and URL claims (htm, htu), a fresh iat, a unique jti (to prevent replay), and that the public key thumbprint equals the cnf.jkt in the access token. Use a library that implements this rather than writing it yourself, and confirm your authorization server supports DPoP.

Machine-to-machine and delegation

For service-to-service calls use the client credentials grant, with short-lived tokens and the narrowest scopes:

curl -s https://auth.example.com/oauth/token \
  -d grant_type=client_credentials \
  -d client_id=billing-worker \
  -d scope="invoices:write" \
  -d audience=https://api.example.com \
  --user "billing-worker:$CLIENT_SECRET"

Prefer private-key JWT or mTLS client authentication over shared secrets where your provider supports it. When a service must call another service on behalf of a user, use token exchange (RFC 8693) or your provider's on-behalf-of flow to obtain a new, narrower token for the downstream audience instead of forwarding the user's original token everywhere. Forwarded tokens create confused-deputy risks and give every downstream service more power than it needs.

For devices without a browser (TVs, CLIs) use the device authorization grant (RFC 8628); for CLIs and desktop apps that can open a browser, use code with PKCE and a loopback redirect or claimed HTTPS link.

OAuth for AI agents and MCP servers

Agents that call tools on a user's behalf are OAuth clients and resource servers like any other. The Model Context Protocol's authorization specification builds on OAuth 2.1: MCP servers act as resource servers that publish protected resource metadata (RFC 9728) pointing to their authorization server, and clients use PKCE and resource indicators so tokens are bound to the specific server. Verify the current MCP authorization spec revision, because it has changed since its first release. The same rules apply: audience validation, no token passthrough, least privilege scopes, and human confirmation for dangerous actions. See securing MCP servers in production, MCP and A2A agent protocols and prompt injection defense for AI agents.

Pitfall: refresh tokens

Refresh tokens are as sensitive as passwords. Good practice:

  • Rotate on every use: each refresh returns a new refresh token and invalidates the old one.
  • Reuse detection: if an old refresh token is presented again, assume theft and revoke the whole token family.
  • Bind to the client; require client authentication for confidential clients.
  • Set absolute and idle lifetimes (for example 30 days absolute, 7 days idle).
  • Never log them.
// Sketch of server-side rotation with reuse detection
async function refresh(presented: string) {
  const row = await db.refreshTokens.findByHash(sha256(presented));
  if (!row) throw new AuthError("invalid_grant");

  if (row.usedAt) {
    await db.refreshTokens.revokeFamily(row.familyId);   // reuse => theft
    throw new AuthError("invalid_grant");
  }

  await db.refreshTokens.markUsed(row.id);
  const next = randomToken();
  await db.refreshTokens.insert({ familyId: row.familyId, hash: sha256(next), userId: row.userId });
  return { access_token: signAccess(row.userId), refresh_token: next };
}

Store only hashes of refresh tokens in your database.

Pitfall: ID token vs access token vs userinfo

  • Use the ID token only to establish who logged in. Validate it (signature, issuer, audience = your client ID, nonce, expiry).
  • Use the access token only to call APIs. Treat it as opaque in the client; only the API should parse it.
  • Do not trust unverified claims like email for account linking. Require email_verified: true, and prefer the stable sub + iss pair as the user identifier. Linking on email alone has caused account-takeover bugs.
  • Request the minimum scopes needed and request more incrementally when features need them.
  • Define scopes at a meaningful granularity (invoices:read not all).
  • For machine-to-machine access, use the client credentials grant with scoped, short-lived tokens, and rotate client secrets or use private-key JWT or mTLS client authentication.

Pitfall: mix-up and discovery

When your app supports multiple identity providers, an attacker can trick it into sending a code to the wrong AS (mix-up attack). Mitigations: store which IdP each login attempt targeted, verify the iss parameter in the authorization response (RFC 9207) where supported, and use per-IdP redirect URIs. Use OIDC discovery (/.well-known/openid-configuration) and cache metadata rather than hardcoding endpoints.

Testing and hardening checklist

  1. Authorization Code + PKCE (S256) everywhere; implicit/password grants disabled at the AS.
  2. Exact-match redirect URIs; no open redirects on your domains.
  3. state and nonce generated, stored, and verified.
  4. JWT validation pins algorithm, issuer, audience, expiry; keys fetched from JWKS with caching and kid rotation handled.
  5. APIs enforce scope and per-resource authorization.
  6. Tokens never in localStorage; BFF with HttpOnly, Secure, SameSite cookies preferred.
  7. Short access-token TTL (5-15 minutes); refresh token rotation with reuse detection.
  8. Logout invalidates server sessions and revokes refresh tokens; also support back-channel logout where available.
  9. Rate limit and monitor the token and login endpoints; alert on refresh reuse and unusual geography.
  10. Run an automated scan (ZAP, Burp) and manual tests for redirect, CSRF, and IDOR cases before launch.

Hands-on lab: run an authorization server locally and break it

Use a local Keycloak (or any OIDC server you can run, such as Authentik or ZITADEL) to practice. This lab covers the discovery document, a PKCE flow and token validation.

docker run --rm -p 8080:8080 \
  -e KC_BOOTSTRAP_ADMIN_USERNAME=admin -e KC_BOOTSTRAP_ADMIN_PASSWORD=admin \
  quay.io/keycloak/keycloak:latest start-dev

Variable names differ between Keycloak versions; check its container guide. Then:

  1. Create a realm demo, a public client my-spa with Standard flow enabled, PKCE method S256, and exact redirect URI http://localhost:3000/callback.
  2. Fetch the discovery document and look at the endpoints and supported algorithms:
curl -s http://localhost:8080/realms/demo/.well-known/openid-configuration | jq '{issuer, authorization_endpoint, token_endpoint, jwks_uri, code_challenge_methods_supported}'
  1. Run the flow from earlier, decode the access token (paste the payload into a JWT debugger or use jq), and confirm iss, aud, exp and scope.
  2. Write the verifyAccessToken function from the JWT validation section against the realm's JWKS and run these negative tests, each of which must fail:
    • A token with the wrong audience.
    • An expired token.
    • A token signed with a different key.
    • A token with alg: none.
    • The ID token presented as an access token.
  3. Try these attacks against your own client and confirm they are blocked: change one character of the registered redirect URI; replay an authorization code twice; send a callback with a wrong state; use a wrong code_verifier.

Turning these into automated tests is the best way to keep the protections in place; see API rate limiting, idempotency and pagination for the surrounding API hardening.

Attack catalog: what each check prevents

Missing controlAttackConsequence
PKCEAuthorization code interceptionAttacker exchanges stolen code for tokens
Exact redirect URIRedirect manipulation, open redirect chainingCode or token sent to attacker
stateLogin CSRFVictim logged into attacker's account
nonceID token replaySession fixation or injection
Audience checkToken confusion, confused deputyA token for API A accepted by API B
Algorithm pinningalg: none, key confusionForged tokens accepted
iss check and RFC 9207IdP mix-upCode sent to wrong server
Refresh rotation and reuse detectionRefresh token theftLong-lived silent access
Per-object authorizationBOLA / IDORUsers read others' data
email_verified and sub + iss identityAccount linking takeoverAttacker claims victim's account
HttpOnly cookies / BFFXSS token theftToken exfiltration
Sender-constrained tokensToken replayStolen token reused elsewhere

Logout, revocation and session management

  • Logging out of your app is not logging out of the identity provider; decide which you mean and use OIDC RP-initiated logout (end_session_endpoint) for the latter.
  • Revoke refresh tokens at logout (RFC 7009 revocation endpoint) and delete the server session.
  • Support back-channel logout if multiple apps share the IdP, so a logout or admin disable propagates.
  • Access tokens that are self-contained JWTs stay valid until exp; keep that short, or add introspection or a revocation list for high-risk operations.
  • Re-authenticate (and request acr or max_age) before sensitive actions such as changing payment details. A passkey step-up is a good fit; see passkeys in production.

Troubleshooting

SymptomLikely cause
invalid_grant on token exchangeCode already used or expired, wrong redirect_uri, or wrong code_verifier
redirect_uri_mismatchTrailing slash, scheme, port or case differs from the registered value
API returns 401 with valid-looking tokenWrong aud or iss (trailing slash differences), clock skew, or JWKS cache not refreshed after key rotation
403 despite valid tokenMissing scope or role claim; check how your IdP maps roles into the token
Works locally, fails behind proxyProxy changes host or scheme, so computed redirect or issuer URLs differ
Silent refresh fails in browsersThird-party cookie restrictions on iframe-based flows; use refresh tokens via a BFF or full redirects
Users get logged out randomlyRefresh rotation race with parallel requests; add a short grace window or a single-flight refresh

When not to build this yourself

Operating an authorization server is a security product in itself. If you do not have a strong reason, use a managed or established open-source provider (Auth0, Okta, Entra ID, Cognito, Keycloak, ZITADEL, Authentik, Clerk and similar), and spend your effort on your API's authorization logic. Build your own only for very specific needs, and then follow the OAuth Security BCP and a conformance test suite (the OpenID Foundation provides one).

Questions that come up

Do I need OAuth for a simple first-party web app? Not necessarily. A server-side session with passkeys or password login can be simpler and safer. Use OAuth and OIDC when you need third-party access, single sign-on, or a separate API audience.

Is the implicit flow ever OK? No; modern browsers and OAuth 2.1 make code with PKCE the replacement.

JWT or opaque access tokens? JWTs let APIs validate locally; opaque tokens let you revoke instantly through introspection. Many systems use JWTs with short lifetimes and opaque refresh tokens.

Where do I store the refresh token in a SPA? Prefer not to have one in the SPA at all: use a BFF. If unavoidable, use rotation, short lifetimes and a strict CSP, and understand the XSS risk.

What is the difference between OIDC and SAML? Both provide federated login; SAML is XML-based and common in enterprise SSO, OIDC is JSON/JWT-based and fits modern web and mobile apps.

How do I rotate signing keys? Publish the new key in the JWKS before using it, keep the old one until all tokens signed with it expire, and make clients refetch the JWKS when they see an unknown kid.

Sources and docs