Last year I was called in to debug an authentication outage that had taken down a partner integration for six hours. The root cause wasn't a code bug — it was an architectural mismatch. The team had used long-lived JWTs as if they were API keys, with no revocation path, and when they needed to rotate a compromised secret, they discovered they couldn't invalidate the tokens already in the wild without deploying a blocklist that defeated the entire purpose of going stateless. That incident perfectly captures why choosing between API keys, JWTs, and OAuth 2.0 isn't about which one is "best" — it's about understanding what each mechanism was actually designed to do, and where it breaks when you stretch it beyond that purpose.
Why API Keys Still Survive in a Token World
Every time a new authentication standard gains traction, someone predicts the death of the API key. Yet in my experience, API keys remain the most common way to authenticate machine-to-machine calls for public APIs, and for good reason. An API key is a single, opaque secret string — typically a long random value like sk_live_51H7x8A2eZvKYlWE7... — that the client sends with every request, usually in a header such as X-API-Key or Authorization: ApiKey .... There is no structure, no claims, no expiry built into the string itself. Validation is a simple lookup: does this key exist, is it active, and what account does it map to?
That simplicity is the entire point. When I built an internal ingestion API for a data pipeline that would only ever be called by three backend services we controlled, JWTs would have added complexity with no benefit. API keys gave us exactly what we needed: a way to identify which service was calling, a way to revoke access instantly by deleting a row in the database, and a way to tie usage to billing. For public APIs where you need to onboard developers quickly, that frictionless model matters. Stripe, AWS, and SendGrid all rely on API keys as the primary entry point for developers for this reason.
The Operational Cost of Opaque Secrets
The tradeoff is that API keys put the burden of state on your server. Every request requires a database or cache lookup. At low to moderate scale this is trivial — a Redis lookup adds 1-2ms — but I have seen teams get surprised when they tried to validate keys against a primary Postgres instance under high throughput. If you go the API key route, plan to cache the key-to-principal mapping and design for prefix-based lookups. Many providers now use a prefixed format like pk_live_ and store only a hash of the secret, similar to how you would store a password. That also lets you show the prefix in logs without leaking the secret.
Where API Keys Fall Short
API keys authenticate the application, not the user. They typically have broad, long-lived permissions and no built-in concept of scopes. If you need to grant a third-party application limited access on behalf of a specific user — for example, letting a calendar app read but not write events — an API key alone forces you to build custom scope logic or issue multiple keys per user. The moment you need delegated authorization or fine-grained, short-lived access, you have outgrown the API key model. That is where structured tokens enter the picture.
JWT Structure and Stateless Validation Under the Hood
A JSON Web Token is not an authentication protocol. It is a token format defined in IETF RFC 7519 that lets you encode claims and verify them cryptographically without contacting the issuer. A JWT has three parts separated by dots: header, payload, and signature, each base64url-encoded. The header declares the algorithm, the payload carries claims like sub, exp, and custom fields, and the signature is computed with a secret (HS256) or private key (RS256/ES256).
The appeal for distributed systems is that any service holding the public key or shared secret can validate the token locally. In my experience this shines in microservice architectures. Our API gateway authenticates the user once, mints a short-lived JWT, and downstream services validate it without a round-trip to an auth service. That cuts latency and removes a single point of failure. But the common claim that JWTs are "stateless" is misleading. They are stateless only until you need revocation, and trust me, you will need revocation.
// Node.js: Validating a RS256 JWT with the 'jose' library
import { jwtVerify, createRemoteJWKSet } from 'jose';
// Cache the JWKS to avoid fetching on every request
const JWKS = createRemoteJWKSet(new URL('https://auth.example.com/.well-known/jwks.json'));
export async function authenticateRequest(req) {
const token = req.headers.authorization?.replace('Bearer ', '');
if (!token) throw new Error('Missing token');
try {
const { payload } = await jwtVerify(token, JWKS, {
issuer: 'https://auth.example.com',
audience: 'api.example.com'
});
// payload now contains { sub, exp, scope, ... }
// Always validate exp, iss, aud - library does this, but understand what it checks
return { userId: payload.sub, scopes: payload.scope.split(' ') };
} catch (err) {
// TokenExpired, JWTInvalid, JWSInvalid etc. - handle explicitly
throw new Error(`Authentication failed: ${err.code}`);
}
}
What Belongs Inside the Payload
I've reviewed countless JWT implementations where developers stuffed half the user profile into the token, pushing it over 4KB and breaking header size limits on load balancers. Be conservative. The payload should contain only what services need for authorization decisions: subject identifier, expiry, issuer, audience, and scopes or roles. Everything else can be fetched on demand. Also, never put sensitive data in a JWT without encryption — the payload is only base64-encoded, not encrypted. Anyone with the token can read it with MDN Web Docs base64 tools. If you need confidentiality, you need a JWE, not a JWS.
Symmetric vs Asymmetric Signing
For internal services where the issuer and verifier are the same application, HS256 with a strong 256-bit secret is fine and fast. For any scenario where multiple independent services need to verify tokens — especially frontends or third-party APIs — use RS256 or ES256. With asymmetric signing, the private key never leaves the authorization server. We rotate our signing keys every 90 days and keep the previous public key in the JWKS for a grace period so existing tokens continue to validate until they expire.
OAuth 2.0 Is a Framework, Not a Protocol: Understanding Grant Flows
One of the most persistent misconceptions I encounter is teams saying they "use OAuth" when they mean they use JWTs, or thinking OAuth 2.0 is a direct competitor to JWTs. It isn't. OAuth 2.0, defined in RFC 6749, is an authorization framework that describes how a client can obtain an access token to act on behalf of a user or itself. That access token is often a JWT, but it could also be an opaque string. OAuth tells you how to get the token; JWT tells you what the token looks like.
What matters in OAuth 2.0 are the grant types, because they map to concrete interaction patterns. In production, I only use three with any regularity. The Authorization Code grant with PKCE is the default for user-facing web and mobile apps — the user is redirected to the authorization server, authenticates, and the app exchanges a code for tokens without ever seeing the user's password. The Client Credentials grant is for service-to-service calls where no user is involved; the service authenticates with its own ID and secret and gets a token for itself. And the Refresh Token flow is how you keep users logged in without making access tokens long-lived.
# Python: Implementing the Authorization Code flow with PKCE
# No external libraries beyond requests - shows the raw HTTP exchange
import hashlib
import base64
import secrets
import requests
# Step 1: Generate code_verifier and code_challenge (client side)
code_verifier = base64.urlsafe_b64encode(secrets.token_bytes(32)).rstrip(b'=').decode()
code_challenge = base64.urlsafe_b64encode(
hashlib.sha256(code_verifier.encode()).digest()
).rstrip(b'=').decode()
# Step 2: Redirect user to authorization endpoint
auth_url = (
"https://auth.example.com/authorize"
f"?response_type=code&client_id=my_app"
f"&redirect_uri=https://app.example.com/callback"
f"&scope=read:profile write:orders"
f"&code_challenge={code_challenge}&code_challenge_method=S256"
)
# Step 3: After redirect, exchange code for tokens
def exchange_code_for_tokens(auth_code: str):
resp = requests.post("https://auth.example.com/token", data={
"grant_type": "authorization_code",
"client_id": "my_app",
"code": auth_code,
"redirect_uri": "https://app.example.com/callback",
"code_verifier": code_verifier
})
resp.raise_for_status()
data = resp.json()
# data = { "access_token": "eyJ...", "refresh_token": "...", "expires_in": 3600 }
return data
Why Client Credentials Replaced Many API Keys
For internal service meshes, I've largely moved from static API keys to OAuth 2.0 Client Credentials. The ergonomics look similar — the calling service sends an ID and secret — but you get short-lived access tokens, scoped permissions, and centralized revocation instead of managing long-lived secrets scattered across environment variables. If a service is compromised, the leaked access token expires in minutes, and you revoke the client at the authorization server. With a static API key, that leak is valid until someone manually rotates it, and in my experience that rotation is often delayed because nobody wants to risk breaking production.
The Complexity Tax
OAuth 2.0 is powerful but it brings significant implementation overhead. You need an authorization server, token endpoints, redirect handling, secure storage for refresh tokens, and client management UI. I have seen small teams spend weeks trying to implement OAuth correctly only to introduce vulnerabilities around redirect validation or token leakage via logs. If you don't need delegation and your API is strictly first-party, you probably don't need full OAuth. A well-implemented JWT issuance endpoint with short expiry may be enough. Don't adopt OAuth because it sounds enterprise-grade; adopt it because you have a delegation problem.
Token Lifecycle Management: Expiry, Rotation, and Revocation Realities
This is the section most tutorials skip and where production systems actually fail. Issuing a token is the easy part. Managing its entire lifecycle is what determines whether your auth system is maintainable.
Expiry strategy is your first decision. I follow a strict short-lived access, long-lived refresh pattern: access tokens live 5-15 minutes, refresh tokens live 7-30 days. The short window limits damage if a token is stolen and makes revocation less critical for access tokens — they simply expire. A common mistake is issuing JWTs valid for 24 hours to avoid implementing refresh logic. That saves a day of development and creates a 24-hour window where a stolen token is fully usable. I learned that the hard way during a pen test where a captured token from a log file remained valid long after the user had logged out.
Revocation Strategies That Actually Work
Pure stateless JWT validation cannot handle revocation. You have three practical options, and I've used all of them in different contexts. First, a blocklist: maintain a Redis set of revoked token IDs (jti) until their natural expiry. This preserves fast local validation for most requests — you only check Redis when a token's jti is in the blocklist, but it reintroduces state. Second, use very short expiry so revocation is less urgent; for logout, you delete the refresh token and let the access token expire within minutes. Third, use opaque refresh tokens and keep JWTs short-lived; revocation then means revoking the refresh token, which is a simple database operation.
For high-security APIs I now prefer the third approach: JWT access tokens with 5-minute expiry plus an opaque, rotatable refresh token stored as an httpOnly, Secure, SameSite=Strict cookie or in secure storage. On refresh, the server rotates the refresh token — invalidating the previous one — which gives you automatic detection of token reuse. If an attacker replays an old refresh token, you can immediately revoke the whole family.
Rotation Without Downtime
Whether you use API keys or JWT signing keys, you need a zero-downtime rotation plan. For API keys, support two active keys per account during a transition window. For JWTs signed with RS256, publish both the old and new public keys in your JWKS; verifiers will try each until one validates. I schedule signing key rotation with a two-week overlap: new tokens are signed with the new key, old tokens signed with the previous key remain valid until they expire. Monitoring how many tokens are still validating against the old key tells you when it's safe to remove it. If you tie rotation to your API Versioning Strategies: URL Path, Header and Query Parameter Approaches planning, you avoid forcing clients to coordinate deployments.
Choosing the Right Mechanism for Service-to-Service vs User-Facing Scenarios
After building APIs that serve both internal microservices and external third-party developers, I've found that the right authentication choice depends almost entirely on who the caller is and what you need to authorize. The technology matters less than the trust boundary.
For public APIs consumed by third-party developers building integrations, API keys are still the best onboarding experience. A developer can generate a key in your dashboard and make a successful call in under a minute. If that API also needs to act on behalf of end users — think a SaaS that integrates with Google Drive — you need OAuth 2.0 Authorization Code flow layered on top. The key identifies the application; the OAuth token authorizes the user's data.
For first-party single-page applications and mobile apps where you control both client and server, OAuth 2.0 with Authorization Code + PKCE issuing JWT access tokens is the current standard. Avoid the Implicit flow — it is deprecated for good reason and exposes tokens in the URL. For server-to-server calls inside your infrastructure, Client Credentials with short-lived JWTs gives you auditable, scoped, auto-expiring credentials without the human login ceremony. And for webhooks or event callbacks where the receiver needs to verify the sender, a signed request with an API key or HMAC signature is often more appropriate than a bearer token.
Getting this decision right early shapes how you design the rest of your system. It influences your REST API Design: Principles That Stand the Test of Time decisions around resource scoping and statelessness, and it directly impacts how you implement usage controls as described in Rate Limiting Patterns for APIs: Token Bucket, Sliding Window and Beyond — because your rate limiter needs to know whether it is throttling per API key, per user, or per OAuth client.
| Criterion | API Keys | JWT (as access token) | OAuth 2.0 |
|---|---|---|---|
| Primary Use Case | Identify and authenticate a project or service | Carry user and scope claims between services | Delegated authorization on behalf of a user or service |
| Validation | Stateful lookup in DB or cache | Stateless signature verification (with optional blocklist) | Depends on token format; framework defines issuance and refresh |
| Expiry & Revocation | Long-lived; instant revocation by deleting key | Short-lived (minutes); revocation requires blocklist or waiting for expiry | Short-lived access token + revocable refresh token; instant revocation at server |
| Carries Identity / Scopes | No — key maps to account externally | Yes — claims like sub, scope, roles embedded | Yes — scopes granted during authorization flow |
| Complexity | Low — easy to issue and use | Medium — needs signing, key distribution, expiry handling | High — authorization server, redirects, grant flows, token management |
| Best When | Simple server-to-server or public API onboarding | Microservices needing decentralized validation | Third-party access to user data or strict least-privilege requirements |
Hardening Authentication: Threat Models I Actually Worry About
Threat modeling for API authentication tends to drift into theory. Here are the specific attacks I have actually remediated in production code reviews, and the mitigations that stuck.
Token leakage via logs is the most common issue I see. Bearer tokens logged as part of a URL or Authorization header end up in ELK stacks, CDN logs, and error trackers. Mitigation: never log the Authorization header. If you need to trace a token, log only its jti or a truncated hash like ...a3f9. Enforce that all API calls use headers, never query parameters, because URLs are logged far more aggressively than headers. For API keys, provide a prefix that can be logged safely.
Replay, Substitution, and Storage
Without TLS, any bearer token is trivially interceptable. That should be obvious in 2026, but I still encounter internal services communicating over plain HTTP "because it's inside the VPC." Don't. Force TLS everywhere and set HTTP Strict Transport Security. On top of TLS, consider binding tokens to a client when the risk justifies it — using mTLS for service-to-service calls or DPoP for user tokens means a stolen token alone is not enough to impersonate the client.
Storage matters just as much. In browsers, never store tokens in localStorage or sessionStorage if you can avoid it; they are accessible to any XSS payload. I've found the most robust pattern for SPA authentication is to keep access tokens in memory and refresh tokens in httpOnly, Secure, SameSite cookies handled by a backend-for-frontend. If you must store tokens client-side, ensure a strong Content Security Policy and short expiry are in place. For server-side clients, load API keys and client secrets from a secrets manager — not from environment files checked into git.
# Python / Flask: Hardened API key validation middleware
import hmac
import hashlib
from functools import wraps
from flask import request, g, jsonify
import redis
redis_client = redis.Redis(host='localhost', port=6379)
def require_api_key(scopes_required=None):
def decorator(f):
@wraps(f)
def wrapped(*args, **kwargs):
# 1. Extract key - never from query params
api_key = request.headers.get('X-API-Key')
if not api_key:
return jsonify(error="Missing API key"), 401
# 2. Constant-time comparison to prevent timing attacks
# Lookup hash, not raw value. Store SHA256(api_key) in DB.
key_hash = hashlib.sha256(api_key.encode()).hexdigest()
cached = redis_client.hgetall(f"api_key:{key_hash}")
if not cached:
# Explicitly use compare_digest even on miss to keep timing uniform
hmac.compare_digest(key_hash, "0" * 64)
return jsonify(error="Invalid API key"), 401
# 3. Check scopes and revocation status
token_scopes = cached.get(b'scopes', b'').decode().split(',')
if scopes_required and not set(scopes_required).issubset(token_scopes):
return jsonify(error="Insufficient scope"), 403
g.client_id = cached.get(b'client_id').decode()
return f(*args, **kwargs)
return wrapped
return decorator
# Usage: @require_api_key(scopes_required=["read:orders"])
Finally, brute force and enumeration are still relevant. Rate limit your token endpoint and your login endpoint separately from your general API rate limits. I return generic 401 Unauthorized responses without indicating whether it was the key ID or the secret that was invalid, and I intentionally add a small random delay on failure to make timing attacks harder. These details rarely appear in architecture diagrams, but they are the difference between a textbook implementation and one that survives real attackers.
Frequently Asked Questions
Can I use JWTs without OAuth 2.0?
Absolutely. JWT is a token format and OAuth 2.0 is a framework for obtaining tokens. Many teams issue JWTs directly from their own login endpoint without implementing full OAuth — for example, after validating a username and password, the server signs a JWT and returns it. This works well for first-party apps where you control both the client and the server. You only need OAuth when you have to delegate access to third-party applications or support multiple grant types. Just be careful to implement the parts OAuth would have given you for free: short expiry, refresh handling, and secure issuance.
Are API keys secure enough for production?
For many use cases, yes, provided you treat them like passwords. That means generating them with a cryptographically secure random generator, storing only a hash on your side, transmitting them only over TLS, and never exposing them in URLs or client-side JavaScript. The limitation is not cryptographic strength but authorization granularity — API keys authenticate the application, not the user, and they tend to be long-lived with broad scopes. If you need per-user consent or fine-grained, short-lived permissions, layer OAuth on top rather than trying to retrofit scopes onto a single static key.
How should I store tokens in a single-page application?
In my experience the safest widely supported approach is to avoid storing tokens in localStorage altogether. Keep the short-lived JWT access token in memory and keep the refresh token in an httpOnly, Secure, SameSite=Strict cookie issued by your backend-for-frontend. That way even if an XSS vulnerability exists, the attacker cannot exfiltrate a long-lived credential. If you must use browser storage, keep expiry very short, enforce a strict Content Security Policy, and ensure tokens are not automatically sent to third-party origins. Never put a refresh token in localStorage.
When should I choose opaque tokens over JWTs?
Choose opaque tokens when you need instant revocation and centralized control. Because an opaque token is just a random string, every validation requires a lookup to the authorization server or cache, which means you can revoke it immediately by deleting it. JWTs trade that instant revocation for decentralized, stateless validation — faster and more resilient, but revocation requires a blocklist or waiting for expiry. I use opaque refresh tokens combined with short-lived JWT access tokens to get the best of both: fast validation for frequent API calls and instant revocation for the longer-lived refresh path.