API Auth Guide
Authentication Method Comparison
| Method | Security | Stateless | Best For |
|---|---|---|---|
| API Key | Medium | ✓ | Server-to-server |
| JWT | High | ✓ | Web/mobile apps |
| OAuth2 | Highest | ✓ | Third-party access |
| Basic Auth | Low (HTTPS required) | ✓ | Simple internal tools |
| mTLS | Highest | ✓ | Zero-trust microservices |
| Session Cookie | High (with HttpOnly) | ✗ | Traditional web apps |
JWT Structure
# JWT = base64(header).base64(payload).signature
# Header
{ "alg": "HS256", "typ": "JWT" }
# Payload (claims)
{
"sub": "user_123",
"iss": "api.example.com",
"iat": 1704067200,
"exp": 1704153600, // expiry (24h later)
"scope": "read:users write:profile"
}
# Usage in HTTP
Authorization: Bearer eyJhbGciOiJIUzI1NiJ9...
OAuth2 Grant Types
# Authorization Code (web apps — most common) 1. Redirect user to /oauth/authorize?client_id=&response_type=code 2. User logs in, gets code 3. Exchange code for access_token (server-side) # Client Credentials (server-to-server) POST /oauth/token grant_type=client_credentials &client_id=xxx&client_secret=yyy &scope=read:data # PKCE (mobile/SPA — no secret exposed) Use code_verifier + code_challenge for security
API Key Best Practices
- ☐ Generate cryptographically random keys (≥32 bytes)
- ☐ Store only the hashed version server-side (bcrypt/SHA-256)
- ☐ Prefix keys with service identifier (sk_prod_xxx)
- ☐ Always send via Authorization header, not URL params
- ☐ Support key rotation without downtime