API Authentication Demystified: API Keys vs Bearer Tokens vs OAuth 2.0
Learn how to secure web APIs using API keys, JWT bearer tokens, and OAuth 2.0 PKCE workflows with complete authentication header examples.
Securing an http api is paramount. Without robust authentication, endpoints can be abused, databases compromised, and server bills inflated. There are three industry-standard authentication patterns for modern web APIs.
1. API Keys (Machine-to-Machine)
The simplest scheme: a unique secret string passed in a request header or query parameter.
GET /api/v1/analytics HTTP/1.1 X-API-Key: cf_live_8923b49f98a7201c
2. JWT Bearer Tokens (Stateless Sessions)
JSON Web Tokens encode user claims, expiration time, and cryptographic signatures in a compact base64 format.
GET /api/v1/user/settings HTTP/1.1 Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIn0...
3. OAuth 2.0 & OpenID Connect (Delegated Authorization)
Used when third-party applications need scoped, revocable access to user data (such as signing in with Google or GitHub) without ever handling the user's raw password. Modern public clients (SPAs and mobile apps) use the Authorization Code Flow with PKCE (Proof Key for Code Exchange) to prevent authorization code interception attacks.
4. Security Trade-offs & Production Checklist
- Never Pass Secrets in URL Query Strings: Query parameters (
?api_key=...) are recorded in plaintext inside reverse-proxy access logs, browser history, and Referer headers. Always use HTTP headers (AuthorizationorX-API-Key). - Keep Access Token TTL Short: Issue stateless JWT access tokens with a 5-to-15 minute expiration (
expclaim) paired with anHttpOnly; Secure; SameSite=Strictrefresh token so compromised sessions can be revoked rapidly.
Frequently Asked Questions (FAQ)
When should I use an API Key instead of a JWT Bearer token?
Use scoped API keys for server-to-server (machine-to-machine) integrations where no interactive human login session exists, and use short-lived OAuth2/JWT Bearer tokens when authenticating end-user browser or mobile sessions.