Implementing Authentication
1. Implementing Basic Authentication
| Property | Value |
|---|---|
| Header | Authorization: Basic base64(user:password) |
| Transport | HTTPS only (credentials sent every request) |
| Use case | Server-to-server, internal APIs |
| Avoid for | Public APIs, browser clients |
2. Implementing Bearer Token Authentication
Example: Bearer Token (JWT)
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.
eyJzdWIiOiI0MiIsImV4cCI6MTc0NzMwNDQwMH0.
sig...
| Token Type | Notes |
|---|---|
| JWT | Self-contained, stateless, signed |
| Opaque token | Server-side lookup required |
| PASETO | JWT alternative, safer defaults |
3. Implementing API Key Authentication
| Location | Example |
|---|---|
| Header (recommended) | X-API-Key: abc123 |
| Authorization header | Authorization: ApiKey abc123 |
| Query param (avoid) | ?api_key=abc123 (logged in URLs) |
Warning: Never put API keys in URLs — they leak via logs, referrer headers, browser history.
4. Implementing OAuth 2.0
| Grant Type | Use Case |
|---|---|
| Authorization Code + PKCE | Web/mobile/SPA (recommended) |
| Client Credentials | Server-to-server (machine) |
| Device Code | TVs, CLI tools |
| Refresh Token | Renew access tokens |
| Implicit DEPRECATED | Replaced by Auth Code + PKCE |
| Password DEPRECATED | Replaced by Auth Code |
5. Implementing OAuth 2.0 Client Credentials
Example: Client Credentials Token Request
POST /oauth/token HTTP/1.1
Content-Type: application/x-www-form-urlencoded
grant_type=client_credentials
&client_id=abc
&client_secret=xyz
&scope=orders:read+orders:write
6. Implementing Session-Based Authentication
| Component | Notes |
|---|---|
| Session cookie | Set-Cookie: sid=...; HttpOnly; Secure; SameSite=Lax |
| Server store | Redis, DB, in-memory |
| CSRF protection | Required (token, SameSite, custom header) |
| Use case | Browser-only apps with same-origin API |
7. Implementing Multi-Factor Authentication
| Factor | Method |
|---|---|
| TOTP | Google Authenticator, Authy (RFC 6238) |
| SMS | Code via text (weak — SIM-swap risk) |
| WebAuthn / Passkeys NEW | Phishing-resistant, hardware-backed |
| Push notification | Approve in companion app |
| Email magic link | Password-less alternative |
8. Handling Token Refresh
Example: Refresh Token Exchange
POST /oauth/token
grant_type=refresh_token&refresh_token=def...
→ {"access_token": "...", "expires_in": 3600, "refresh_token": "new..."}
| Best Practice | Reason |
|---|---|
| Rotate refresh tokens | Detect token theft |
| Detect reuse → revoke family | Replay attack mitigation |
| Long-lived (days/weeks) | Access tokens stay short-lived (15-60 min) |
9. Implementing Token Expiration
| Token | Typical Lifetime |
|---|---|
| Access token | 15-60 minutes |
| Refresh token | 7-90 days |
| ID token | Same as access |
| API key (long-lived) | Months/years; rotate periodically |
10. Securing Authentication Endpoints
| Protection | Implementation |
|---|---|
| Rate limiting | Per IP + per username |
| Account lockout | After N failed attempts |
| CAPTCHA | After threshold |
| Generic error | "Invalid credentials" — not "user exists" |
| Constant-time comparison | Prevent timing attacks |
| Logging | All auth attempts (no passwords) |
11. Handling Authentication Errors
| Status | Cause | WWW-Authenticate |
|---|---|---|
| 401 | Missing/invalid/expired token | Bearer realm="api", error="invalid_token" |
| 401 | Token expired | error="invalid_token", error_description="expired" |
| 403 | Token valid but lacks scope | error="insufficient_scope", scope="orders:write" |