Difficulty: Intermediate
Compare API keys, OAuth 2.0 and JWT for API authentication. When would you use each?
First, untangle the terms, because interviewers often bait candidates into comparing things that are not the same kind. API keys and OAuth 2.0 are approaches to obtaining and presenting credentials. JWT is a token format. OAuth 2.0 access tokens are frequently JWTs, but do not have to be.
An API key is a long random secret that identifies a calling application or account. The client sends it in a header such as Authorization: Bearer or X-API-Key. It is like a house key: whoever holds it gets in. It is simple, great for server to server calls, developer onboarding and machine clients, and it is how Razorpay and Stripe secure their merchant APIs (key id plus secret over HTTPS). Weaknesses: it identifies the app, not a particular end user; it has no built-in expiry or scoping unless you build it; if it leaks it is valid until revoked. Mitigations: hash keys at rest like passwords, show them once, support rotation and multiple keys, prefix them to make secret scanners effective, restrict by scope or IP, and never put them in URLs or client-side code.
OAuth 2.0 is an authorization framework for delegated access. It lets a user grant a third-party app limited access to their data without sharing their password. Think of a hotel key card that opens only your room and expires at checkout, instead of handing over the master key. Roles: resource owner (user), client (app), authorization server (issues tokens) and resource server (your API). The modern recommended flow for user-facing apps is Authorization Code with PKCE, including for SPAs and mobile apps. Client Credentials is for machine to machine access with no user. The implicit and password grants are deprecated. Tokens carry scopes such as read:orders, are short lived, and can be paired with refresh tokens. Use OAuth when third parties integrate on behalf of users, when you need fine-grained scopes and revocation, or when you need single sign-on via OpenID Connect layered on top.
JWT, JSON Web Token, is a compact signed token in three base64url parts: header, payload with claims like sub, iss, aud, exp, scope, and signature. Because it is self-contained, the resource server can verify it locally using the issuer's public key (RS256 or ES256) without a database lookup, which is attractive for microservices. Downsides: you cannot easily revoke a JWT before expiry, so keep lifetimes short and use a denylist or rotating refresh tokens for logout; never store sensitive data in the payload because it is only encoded, not encrypted; always verify signature, exp, iss and aud; reject alg none and pin the expected algorithm. The alternative is an opaque token checked by introspection with the authorization server, giving instant revocation at the cost of a network call or cache.
Decision guide: public developer API for backend integrations, API keys, possibly with OAuth client credentials for larger customers. Third-party apps acting for end users, OAuth 2.0 authorization code with PKCE. First-party web or mobile app talking to your own backend, short lived access tokens (JWT) plus refresh tokens, or plain secure cookies for a same-site web app. Internal service to service, mTLS or signed JWTs from a workload identity system.
Whichever you choose, use HTTPS only, send credentials in the Authorization header, rate limit authentication endpoints, log authentication failures without logging secrets, and return 401 with WWW-Authenticate on failure.
A crisp closing line: API keys identify applications, OAuth authorizes delegated access, and JWT is one way to package the token.
import jwt from 'jsonwebtoken';
export function requireAuth(req, res, next) {
const h = req.header('Authorization') ?? '';
const token = h.startsWith('Bearer ') ? h.slice(7) : null;
if (!token) return res.status(401).set('WWW-Authenticate', 'Bearer').json({ title: 'Missing token' });
try {
req.auth = jwt.verify(token, PUBLIC_KEY, {
algorithms: ['RS256'],
issuer: 'https://auth.example.com',
audience: 'orders-api'
});
next();
} catch {
res.status(401).set('WWW-Authenticate', 'Bearer error="invalid_token"').json({ title: 'Invalid or expired token' });
}
}
Pins the algorithm, checks issuer and audience, and returns a proper 401 challenge.
authentication, API keys, OAuth 2.0, JWT