
API Authentication Methods: Keys, Tokens, and OAuth
Deep dive into every API authentication method. Compare API keys, JWT Bearer tokens, Basic Auth, and OAuth 2.0 with implementation examples and security best practices.
API Authentication Methods: Keys, Tokens, and OAuth
Authentication is the gatekeeper of every real-world API. This lesson goes deep on each method — when to use it, how it works under the hood, security implications, and hands-on implementation. By the end, you will confidently authenticate against any API.
1. Why Authentication Matters
Without authentication, an API is exposed to:
| Risk | Consequence |
|---|---|
| Unauthorized data access | Anyone reads your users' data |
| Data manipulation | Anyone modifies or deletes resources |
| Abuse and overload | Bots flood the API with requests |
| No usage tracking | Cannot bill, rate-limit, or audit |
| Impersonation | Anyone acts as any user |
2. API Keys — The Simple Approach
An API key is a unique string assigned to each developer/application.
How API Keys Work
sequenceDiagram
participant Dev as Developer
participant Portal as API Portal
participant API as API Server
Dev->>Portal: Sign up and create app
Portal-->>Dev: API Key: sk_abc123
Dev->>API: Request + API Key
API->>API: Look up key in database
API-->>Dev: Response
Implementation
In a header:
curl -H "X-API-Key: sk_live_abc123def456" \
https://api.example.com/data
In a query parameter:
curl "https://api.openweathermap.org/data/2.5/weather?q=London&appid=YOUR_KEY"
Real-World Examples
| API | Key Location | Header Name |
|---|---|---|
| OpenWeatherMap | Query param | appid |
| Google Maps | Query param | key |
| SendGrid | Header | Authorization: Bearer SG.xxx |
| Stripe | Header | Authorization: Bearer sk_test_xxx |
Security
| Do | Do Not |
|---|---|
| Store keys in environment variables | Hardcode keys in source code |
| Use HTTPS always | Send keys over HTTP |
| Rotate keys periodically | Share keys publicly |
| Use different keys per environment | Use production keys in development |
| Restrict key permissions | Give full access to all keys |
3. JWT Bearer Tokens — The Modern Standard
JWT (JSON Web Token) is a self-contained token that encodes user identity.
JWT Structure
A JWT is three Base64-encoded parts separated by dots:
eyJhbGciOiJIUzI1NiJ9.eyJ1c2VySWQiOjQyLCJyb2xlIjoiYWRtaW4ifQ.SflKxwRJSMeKKF2QT4fwpM
├── Header ──────────────┤├── Payload ────────────────────────────────┤├── Signature ──────────┤
Header:
{
"alg": "HS256",
"typ": "JWT"
}
Payload:
{
"userId": 42,
"role": "admin",
"email": "admin@example.com",
"iat": 1708617000,
"exp": 1708620600
}
iat= issued at (Unix timestamp)exp= expires at (Unix timestamp)
Signature: A cryptographic hash that verifies the token has not been tampered with.
JWT Authentication Flow
sequenceDiagram
participant Client
participant Auth as Auth Server
participant API as API Server
Client->>Auth: POST /login {email, password}
Auth->>Auth: Verify credentials
Auth->>Auth: Generate JWT
Auth-->>Client: {token: "eyJ...", expiresIn: 3600}
Client->>API: GET /data<br/>Authorization: Bearer eyJ...
API->>API: Decode and verify JWT
API->>API: Check expiration
API->>API: Extract userId from payload
API-->>Client: 200 OK + data
Implementation
# Step 1: Login
TOKEN=$(curl -s -X POST https://api.example.com/auth/login \
-H "Content-Type: application/json" \
-d '{"email":"user@test.com","password":"secret"}' | jq -r '.token')
# Step 2: Use the token
curl -H "Authorization: Bearer $TOKEN" \
https://api.example.com/users/me
# Step 3: Refresh when expired
NEW_TOKEN=$(curl -s -X POST https://api.example.com/auth/refresh \
-H "Authorization: Bearer $TOKEN" | jq -r '.token')
Token Refresh Pattern
graph LR
A["Login"] --> B["Access Token<br/>(15 min)"]
A --> C["Refresh Token<br/>(7 days)"]
B --> D{Expired?}
D -->|No| E["Make API Calls"]
D -->|Yes| F["Use Refresh Token"]
F --> G["New Access Token"]
G --> E
style B fill:#059669,color:#fff
style C fill:#0891b2,color:#fff
style G fill:#059669,color:#fff
4. Basic Authentication — The Legacy Method
Basic Auth sends username and password with every request, Base64-encoded.
# Using -u flag
curl -u admin:secretpassword https://api.example.com/data
# Equivalent manual header
# Base64("admin:secretpassword") = "YWRtaW46c2VjcmV0cGFzc3dvcmQ="
curl -H "Authorization: Basic YWRtaW46c2VjcmV0cGFzc3dvcmQ=" \
https://api.example.com/data
When to Use
- Internal tools and admin interfaces
- Integration with legacy systems
- Simple testing scenarios
When NOT to Use
- Public-facing APIs (use JWT instead)
- Mobile applications
- Any non-HTTPS connection
Critical: Base64 is encoding, NOT encryption. Anyone can decode it. Always use HTTPS with Basic Auth.
5. OAuth 2.0 — Delegated Access
OAuth 2.0 lets users grant limited access to their data on one service to another service, without sharing their password.
Example: "Sign in with Google" lets an app access your Google profile without knowing your Google password.
OAuth 2.0 Flow (Authorization Code)
sequenceDiagram
participant User
participant App as Your App
participant Auth as Auth Provider (Google)
participant API as API (Google)
User->>App: Click "Sign in with Google"
App->>Auth: Redirect to Google login
Auth->>User: Show login page
User->>Auth: Enter credentials + approve
Auth-->>App: Authorization code
App->>Auth: Exchange code for token
Auth-->>App: Access token + refresh token
App->>API: GET /userinfo + access token
API-->>App: User profile data
OAuth 2.0 Grant Types
| Grant Type | Use Case |
|---|---|
| Authorization Code | Web apps (most secure) |
| Client Credentials | Server-to-server (no user involved) |
| PKCE | Mobile and SPA apps |
| Implicit | Deprecated — do not use |
OAuth 2.0 is complex and beyond what beginners typically implement, but you should know it exists and how it works at a high level.
6. Comparison Table
| Feature | API Key | JWT | Basic Auth | OAuth 2.0 |
|---|---|---|---|---|
| Complexity | Low | Medium | Low | High |
| Security | Medium | High | Low | Very High |
| Expiration | Manual | Built-in | None | Token-based |
| User context | No | Yes | Yes | Yes |
| Stateless | Yes | Yes | No | Depends |
| Best for | Server-to-server | Web/mobile apps | Internal tools | Third-party access |
Summary and Key Takeaways
- API Keys are simple but limited — best for server-to-server communication.
- JWT Bearer Tokens are the modern standard with built-in expiration and user context.
- Basic Auth sends credentials with every request — only use over HTTPS.
- OAuth 2.0 enables third-party access without sharing passwords.
- Always use HTTPS when sending any form of credentials.
- Store keys and tokens in environment variables, never in source code.
Lesson Review Quiz
?Knowledge Check
What information is encoded in a JWT payload?
?Knowledge Check
What does the 'exp' claim in a JWT represent?
?Knowledge Check
Why should you NEVER use Basic Auth over HTTP (without HTTPS)?