API Authentication
API authentication is the process of verifying that a request comes from an authorized client. Your API must verify every request before processing it. Without authentication, anyone can call your API and do anything.
How API Authentication Works
The client proves its identity. The server verifies the proof. If valid, the request is processed. If invalid, return 401 Unauthorized. This happens on every request.
API Keys
API keys are long random strings. The client includes the key in every request. The server looks up the key, verifies it's valid, and processes the request.
API keys are simple. Store the key hashed in the database (never plain text). Include it in the Authorization header: Authorization: Bearer abc123. Or as a query parameter: ?api_key=abc123 (less secure, but works).
Downsides: API keys don't expire by default. If a key leaks, you must rotate it. Keys have no scope—a compromised key gives full access. Better for server-to-server communication or developer access, not for user-facing APIs.
Bearer Tokens (JWT or Opaque)
Bearer tokens are typically JWTs (JSON Web Tokens) or opaque tokens. JWT is self-contained—the token itself contains information (user ID, permissions). Opaque tokens require a server lookup.
JWTs are signed, so you can verify them without a database lookup. They're efficient. The downside: JWTs are harder to revoke. An attacker with a token has access until it expires.
Include tokens in the Authorization header: Authorization: Bearer eyJhb... Most web frameworks automatically extract and verify bearer tokens.
OAuth 2.0 for API Access
OAuth 2.0 allows external apps to act on behalf of users. You see "Login with Google" everywhere. OAuth handles both authentication (proving who you are) and authorization (what you're allowed to do).
The user authorizes the app to access their data. The app gets a token. The token is scoped—it can read data but not write, or access specific resources. This is more secure than passwords or blanket API keys.
Scope-Based Access
Tokens can have scopes that limit what the token can do. A token with "read:user" scope can read user data but not modify it. A token with "write:post" scope can create posts.
Scopes are a best practice. Always scope tokens to the minimum permissions needed. If a token is compromised, the damage is limited to what the token's scopes allow.
Token Expiry and Refresh
Access tokens should be short-lived. 15 minutes, 1 hour, even shorter for sensitive operations. If a token is stolen, it's only useful for that window.
Refresh tokens are separate, long-lived tokens that let you get new access tokens without re-authenticating. User logs in once (refresh token issued). The refresh token is stored securely and used to get new access tokens as needed.
This is safer than long-lived access tokens. If an access token leaks, it expires soon. The refresh token remains secure.
Rate Limiting and API Keys
Tie rate limits to API keys. Each key has a limit—1,000 requests per hour, for example. This prevents abuse. A compromised key can be rate-limited before too much damage. Rate limits also prevent your service from being overloaded by bad clients.
CORS: Cross-Origin Resource Sharing
Browsers restrict which origins (domains) can call APIs from other origins. If example.com's JavaScript calls api.example.com, the browser allows it (same origin). If example.com's JavaScript calls api.other-domain.com, the browser blocks it by default.
APIs can whitelist origins with CORS headers. Access-Control-Allow-Origin: https://example.com allows example.com to call the API from the browser. Without this, cross-origin requests fail.
Protecting API Credentials
Never expose API credentials in browser-visible code (JavaScript). Anything in browser code is extractable. API keys must be server-side only.
For public-facing APIs where the browser calls the API directly (like a maps API), use browser-restricted keys that only allow specific operations, or require OAuth so users authenticate themselves, not your app.
HTTPS Only
Always use HTTPS for APIs. Credentials in HTTP can be intercepted. This is non-negotiable. Every API call must be over HTTPS.
| Method | Best For | Pros | Cons |
|---|---|---|---|
| API Key | Server-to-server, developers | Simple, easy | No expiry, high-privilege |
| Bearer Token (JWT) | User APIs | Self-contained, efficient | Hard to revoke |
| Bearer Token (Opaque) | User APIs | Revocable, flexible | Requires DB lookup |
| OAuth 2.0 | Delegated access | Secure, scoped, standard | Complex setup |
| mTLS | Service-to-service | Mutual authentication, secure | Certificate management overhead |