How Does API Authentication Work? Understanding API Keys, Tokens, and OAuth
When you use an app to check the weather, post on social media, or access your bank account, the app needs to prove it has permission to access that data on your behalf. This is where API authentication comes in — the security layer that ensures only authorized applications and users can access protected resources.
Understanding API authentication is crucial for anyone working with modern applications. Whether you’re integrating with third‑party services, building your own APIs, or simply curious about how app security works, these authentication methods are the gatekeepers that keep the digital world secure.
Authentication vs Authorization: The Important Distinction
Section titled “Authentication vs Authorization: The Important Distinction”- Authentication: Who are you? Verifying identity
- Authorization: What can you do? Determining permissions
Example
- Authentication: The app verifies you are who you claim to be (username and password)
- Authorization: The system checks what you’re allowed to do (read, write, admin)
Most API auth schemes touch both, but they solve different problems.
The Building Security Analogy
Section titled “The Building Security Analogy”- API Keys: Basic key cards that open specific doors
- Bearer Tokens: Temporary visitor badges with time limits
- OAuth: Valet system where you grant limited access without sharing your actual keys
API Keys: The Digital Key Card
Section titled “API Keys: The Digital Key Card”Simple, long‑lived credentials that identify and authenticate your application.
How API Keys Look
Section titled “How API Keys Look”GET /api/v1/resources HTTP/1.1Host: [api.example.com](http://api.example.com)X-API-Key: sk_live_abc123def456Common Implementation Patterns
Section titled “Common Implementation Patterns”- Header‑based (most common)
curl -H "X-API-Key: YOUR_KEY" https://api.example.com/api/v1/resources- Query parameter (insecure — avoid)
curl "https://api.example.com/api/v1/resources?api_key=YOUR_KEY"⚠️ Never put keys in URLs. They leak into server logs, browser history, analytics, and referrer headers.
- Authorization header (some providers)
curl -H "Authorization: Bearer YOUR_KEY" https://api.example.com/api/v1/resourcesWhen to Use
Section titled “When to Use”- Server‑to‑server integrations
- Simple internal services
- Public or low‑risk data
Security Notes
Section titled “Security Notes”- Never expose keys in client‑side code
- Always use HTTPS
- Rotate keys and scope permissions narrowly
Basic Authentication (Legacy)
Section titled “Basic Authentication (Legacy)”A very old pattern that encodes username:password in Base64. Avoid for modern APIs.
Authorization: Basic dXNlcm5hbWU6cGFzc3dvcmQ=Base64 is not encryption; it’s easily reversible. If you must support it, require HTTPS, short lifetimes, and limited scopes.
Bearer Tokens: Temporary Access Passes
Section titled “Bearer Tokens: Temporary Access Passes”Short‑lived credentials (often JWTs) presented in the Authorization header.
How They Look
Section titled “How They Look”GET /api/v1/user/profile HTTP/1.1Host: [api.example.com](http://api.example.com)Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...JSON Web Tokens (JWT)
Section titled “JSON Web Tokens (JWT)”Many bearer tokens use the JWT format: header.payload.signature
- Header:
{"alg":"HS256","typ":"JWT"} - Payload:
{"user_id":123,"exp":1640995200} - Signature: cryptographic verification
What the signature prevents
- Detects tampering: if someone edits the header or payload, signature verification fails
- Proves authenticity: only the signer (or key holder) can produce a valid signature
Note: JWTs are only as trustworthy as your key management and verification logic. Never trust a JWT you haven’t verified.
Token Lifecycle and Refresh Flow
Section titled “Token Lifecycle and Refresh Flow”- User authenticates with credentials or an OAuth grant
- Server issues a short‑lived access token and a longer‑lived refresh token
- Client calls APIs with the access token in Authorization: Bearer …
- When the access token expires, the client exchanges the refresh token for a new access token
- Server may rotate refresh tokens and revoke old ones
Benefits: short access token lifetimes reduce risk; refresh tokens let sessions continue without prompting for credentials.
When to Use
Section titled “When to Use”- User‑specific data and permissions
- Mobile and SPA frontends
- Anywhere you want automatic expiration and revocation
OAuth 2.0: The Valet System
Section titled “OAuth 2.0: The Valet System”A framework for granting limited access without sharing passwords.
Participants (plain language)
- User: the person who owns the data
- Client app: the app asking for limited access
- Authorization server: the place the user signs in and grants consent
- Resource server: the API that holds the data
Concrete flow (Authorization Code with PKCE, simplified)
- App sends user to the authorization server with requested scopes
- User signs in and reviews the requested access
- User consents; authorization server redirects back with a one‑time code
- App’s backend exchanges the code for tokens (access token, optionally refresh token)
- App calls the resource server using Authorization: Bearer ACCESS_TOKEN
- When the access token expires, app uses the refresh token to get a new access token (until revoked or expired)
Security benefits
- The app never sees the user’s password
- Users can grant only specific scopes and revoke later
- Short‑lived access tokens, refresh‑based continuation
Common Authentication Errors
Section titled “Common Authentication Errors”- 401 Unauthorized: Missing or invalid credentials. Fix by including valid Authorization headers or signing in.
- 403 Forbidden: You are authenticated, but lack permission for this resource or action. Fix by requesting proper scopes or roles.
Best Practices Across All Methods
Section titled “Best Practices Across All Methods”- Always use HTTPS
- Keep secrets out of URLs and client‑side code
- Scope credentials narrowly and rotate them
- Prefer short‑lived access tokens plus refresh tokens
- Verify JWTs server‑side and validate exp, aud, iss, and signature
- Log auth failures with enough context, but never log secrets
Common Pitfalls
Section titled “Common Pitfalls”- Putting keys in frontend code or mobile apps
- Long‑lived tokens with no rotation
- Accepting JWTs without verifying signature and claims
- Using 200 responses for auth failures instead of proper 401 or 403
Quick Reference Examples
Section titled “Quick Reference Examples”Header API key
X-API-Key: sk_live_abc123Bearer token
Authorization: Bearer eyJhbGciOi...Basic auth (legacy)
Authorization: Basic dXNlcm5hbWU6cGFzc3dvcmQ=JWT structure (compact)
header.payload.signatureOfficial Resources
Section titled “Official Resources”Consult these authoritative sources to learn more:
- OWASP Authentication Cheat Sheet: Comprehensive security best practices. Industry‑standard guidance for secure implementation.
- RFC 6749 — The OAuth 2.0 Authorization Framework: The foundational OAuth specification from IETF. Essential for understanding OAuth concepts and flows.
- RFC 7519 — JSON Web Token (JWT): Official JWT specification. Critical for understanding token structure and validation.
- RFC 6750 — Bearer Token Usage: Official specification for bearer tokens. Defines proper use of Authorization: Bearer headers.
Top 5 Software Engineering Interview Q&A
Section titled “Top 5 Software Engineering Interview Q&A”- What’s the difference between authentication and authorization?
- Authentication answers “Who are you?” using proofs like passwords, OTPs, or federated identities. Authorization answers “What are you allowed to do?” via roles, scopes, and policies. In code, authN typically happens at the edge (middleware) to establish a principal, and authZ is enforced per route or resource with RBAC/ABAC checks. Tests should cover both: rejected requests without identity, and denied requests with insufficient permission.
- Why are API keys in query parameters insecure?
- URLs are widely logged by proxies, servers, CDNs, and browsers, so keys in query strings leak into logs, history, analytics, and referrer headers. They’re also easier to shoulder‑surf and accidentally share. Prefer headers over HTTPS, disable query‑string auth, and redact query strings in logs. If you must support legacy clients, gate by IP, apply strict rate limits, and migrate to headers ASAP.
- What does a JWT signature actually protect?
- Integrity and authenticity. A valid signature proves the token was issued by a trusted signer and has not been altered (header or payload). It does not provide confidentiality; JWT payloads are usually base64url‑encoded, not encrypted. In services, always verify signature,
exp,iss,aud, and optionallynbf. Rotate signing keys, use strong algorithms (avoidnone), and reject tokens signed with unexpected algs.
- When do you choose OAuth over simple bearer tokens?
- Use OAuth when a third‑party identity or consented access is required, such as “Sign in with X” or accessing a user’s data at another provider. OAuth provides scoped, revocable access and separates the roles of authorization server and resource server. For first‑party apps with no external identity, a simple login plus server‑issued bearer tokens may suffice.
- How does a refresh token flow work and why use it?
- The server issues a short‑lived access token and a longer‑lived refresh token. Clients call APIs with the access token; when it expires, they exchange the refresh token for a new access token (often rotating the refresh token). Benefits: limits exposure if an access token leaks, reduces re‑authentication prompts, and supports session revocation by invalidating refresh tokens. Store refresh tokens securely (httpOnly cookies or secure storage), bind them to client context if possible, and monitor unusual reuse patterns.
-
What’s the difference between authentication and authorization?
Authentication verifies who you are (like showing ID), while authorization determines what you’re allowed to do (like having permission to enter a room). APIs need both: auth proves identity, authz grants access.
-
Which authentication method should I use for my API?
Use API keys for server-to-server communication, OAuth for third-party user data access, and JWT tokens for stateless distributed systems. Always use HTTPS regardless of method.
-
Are API keys safe to use in mobile apps?
No. Never embed API keys in client-side code or mobile apps - they can be extracted through reverse engineering. Use a backend proxy to make authenticated API calls.
-
How often should I rotate API keys?
Rotate keys every 90 days minimum, immediately after team member departures, and whenever there’s a potential security breach. Use automated key rotation for production systems.
-
What’s the difference between access tokens and refresh tokens?
Access tokens are short-lived (minutes to hours) and used to access resources. Refresh tokens are long-lived and used only to obtain new access tokens, reducing exposure if an access token is compromised.