API Security · intermediate · ~12 min

API authentication, tokens, and OAuth

Explain API auth schemes, token-handling pitfalls, and OAuth basics.

Overview

APIs use tokens (API keys, bearer/JWT, OAuth) not cookies. Pitfalls: token leakage (URLs, storage, repos), missing expiry/revocation, over-scoping. OAuth 2.0 delegates authorization via access/refresh tokens; watch redirect_uri validation, the state parameter, and scope. Fix: short-lived scoped tokens, strict redirect allowlists, header-only transport.

Why it matters

Token mishandling is a leading cause of API compromise — a leaked or over-scoped token is instant access, and OAuth redirect/state flaws enable account takeover. Knowing the schemes tells you where to look.

Core concepts

Schemes. API keys, bearer/JWT, OAuth. Leakage vectors. URLs, client storage, errors, repos. Token hygiene. Short-lived, scoped, revocable, header-only. OAuth pitfalls. redirect_uri validation, missing state (CSRF), implicit flow, broad scopes.

Lesson

APIs authenticate with tokens rather than session cookies, which changes the failure modes.

Schemes you'll meet

  • API keys — a static secret per client; often over-permissioned and leaked in code/URLs.
  • Bearer tokens / JWT — sent in Authorization: Bearer .... (JWT-specific flaws — alg:none, weak secrets, alg confusion — are in the Web App Security track; they apply here directly.)
  • OAuth 2.0 — delegated authorization (below).

Token-handling pitfalls

  • Leakage: tokens in URLs (logged, in Referer), in client-side storage exposed to XSS, in error messages, or committed to repos.
  • No/!expiry: long-lived or never-expiring tokens; no revocation.
  • Over-scoped tokens: one token that can do everything.
  • Sent to the wrong host: a token meant for API A leaked to API B.

OAuth 2.0 in one paragraph

OAuth lets a user grant an app limited access to their data on another service without sharing their password, via an authorization flow that returns an access token (and often a refresh token). It's authorization delegation, frequently misused for authentication. Common issues: weak/secretless flows (implicit), missing/loose redirect_uri validation (token theft via open redirect), missing state (CSRF on the callback), and over-broad scopes.

Fixes

Short-lived, narrowly-scoped tokens; strict redirect_uri allowlisting; state on flows; tokens only in headers (never URLs); server-side validation of issuer/audience/expiry.

Summary

API auth rests on tokens, so the risks shift to leakage, lifetime, and scope, plus OAuth-specific redirect/state/scope flaws. Defenses are short-lived narrowly-scoped tokens, strict redirect allowlisting, the state parameter, and header-only transport.