← Back to Backend, page 1

backend-0014 · Hard senior

What are the common security mistakes in OAuth 2.0 and OIDC implementations (redirect URI matching, state, implicit flow, token storage), and how do you prevent them?

The usual failures are: loose redirect URI matching (an attacker gets the code or token at their own URL), a missing state check (login CSRF), the implicit flow and tokens in URLs, missing PKCE, tokens stored where scripts can read them, accepting tokens for the wrong audience, and over-broad scopes. Prevent them with exact redirect URI comparison, state and PKCE on every login, the code flow only, short-lived tokens with rotation, audience checks, and server-side or HttpOnly cookie handling of tokens.

Full answer
  1. Redirect URI matching: the authorization server must compare the whole URI to a registered one, character by character. Prefix, wildcard or domain-only matching lets attackers use open redirects or look-alike hosts (https://app.example.com.evil.com) to receive the code.
  2. state (login CSRF): without it an attacker can make a victim's browser finish the attacker's login, linking the attacker's account. Generate state per request, bind it to the user's session, check it on the callback.
  3. Implicit flow and response_type=token: tokens appear in URLs, history and logs. OAuth 2.1 removes it. Use the code flow with PKCE.
  4. PKCE downgrade: if the server accepts an exchange when no challenge was sent, an attacker can skip PKCE. Require it for public clients, and reject the plain method.
  5. Token storage: tokens in localStorage can be stolen by any XSS. Prefer a backend for frontend (BFF) that keeps tokens server-side and gives the browser an HttpOnly, Secure, SameSite session cookie. Mobile apps use the OS secure storage.
  6. Audience and scope: APIs must check aud and scope. Do not accept ID tokens as access tokens. Request the least scope.
  7. Refresh tokens: rotate them on use and detect reuse (revoke the family). Bind or limit them for public clients.
  8. Mix-up and confused deputy: with several providers, check the iss of the response, and keep redirect URIs per provider.
  9. Open redirectors in your own app, tokens in logs and referrer headers, and long-lived tokens are common leak routes.
javascript
const registered = ['https://app.example.com/callback'];
const prefixMatch = (uri) => registered.some((r) => uri.startsWith(new URL(r).origin));       // a weak check
const exactMatch = (uri) => registered.includes(uri);                                          // the right check

const attempts = [
  'https://app.example.com/callback',
  'https://app.example.com.evil.net/callback',
  'https://app.example.com/callback/../open-redirect?to=https://evil.net',
  'https://app.example.com/other',
  'https://evil.net/callback',
];
console.log('redirect_uri'.padEnd(72), 'weak  exact');
for (const uri of attempts) console.log(uri.padEnd(72), String(prefixMatch(uri)).padEnd(5), exactMatch(uri));

// state is stored in the user's session at the start, and compared on the callback.
const sessionState = 'a1b2c3';
const callback = (queryState) => (queryState && queryState === sessionState ? 'continue login' : 'reject: state missing or different');
console.log('\ncallback with the right state :', callback('a1b2c3'));
console.log('callback forged by an attacker:', callback('zzz'));
console.log('callback with no state        :', callback(undefined));

// Token checks an API must do on every request
function checkAccessToken(claims, { audience, scope, now }) {
  if (claims.aud !== audience) return 'reject: token is for another API';
  if (claims.exp <= now) return 'reject: expired';
  if (!claims.scope.split(' ').includes(scope)) return 'reject: scope missing';
  return 'allow';
}
const now = 1_800_000_000;
console.log('\nright audience and scope      :', checkAccessToken({ aud: 'api://students', exp: now + 60, scope: 'read write' }, { audience: 'api://students', scope: 'read', now }));
console.log('ID token used as access token :', checkAccessToken({ aud: 'my-client', exp: now + 60, scope: 'openid' }, { audience: 'api://students', scope: 'read', now }));
console.log('token with too little scope   :', checkAccessToken({ aud: 'api://students', exp: now + 60, scope: 'read' }, { audience: 'api://students', scope: 'write', now }));

Pure functions that compare a weak and an exact redirect URI check, a state check and an access token check. No network is used. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, run once): redirect_uri weak exact https://app.example.com/callback true true https://app.example.com.evil.net/callback true false https://app.example.com/callback/../open-redirect?to=https://evil.net true false https://app.example.com/other true false https://evil.net/callback false false callback with the right state : continue login callback forged by an attacker: reject: state missing or different callback with no state : reject: state missing or different right audience and scope : allow ID token used as access token : reject: token is for another API token with too little scope : reject: scope missing

Key points

  • Compare redirect URIs exactly.
  • Always use state and PKCE; use the code flow only.
  • Keep tokens out of JavaScript reachable storage when you can.
  • Check audience and scope in every API.
  • Rotate refresh tokens and detect reuse.

Common mistakes

  • Registering http://localhost and wildcards in production.
  • Treating a valid token as proof of permission without scope checks.
  • Keeping long-lived access tokens in localStorage.
  • Allowing the implicit flow because an old library does.
  • Logging full callback URLs (codes and tokens end up in logs).

Follow-ups

  • What is a backend for frontend (BFF)?
  • How does refresh token reuse detection work?
  • What changed from OAuth 2.0 to OAuth 2.1?

Tips

  • Name the attack for each pitfall.
  • Mention the BFF.
  • End with token validation at the API.