Implementing Authentication

1. Implementing Basic Authentication

PropertyValue
HeaderAuthorization: Basic base64(user:password)
TransportHTTPS only (credentials sent every request)
Use caseServer-to-server, internal APIs
Avoid forPublic APIs, browser clients

2. Implementing Bearer Token Authentication

Example: Bearer Token (JWT)

Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.
                       eyJzdWIiOiI0MiIsImV4cCI6MTc0NzMwNDQwMH0.
                       sig...
Token TypeNotes
JWTSelf-contained, stateless, signed
Opaque tokenServer-side lookup required
PASETOJWT alternative, safer defaults

3. Implementing API Key Authentication

LocationExample
Header (recommended)X-API-Key: abc123
Authorization headerAuthorization: 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 TypeUse Case
Authorization Code + PKCEWeb/mobile/SPA (recommended)
Client CredentialsServer-to-server (machine)
Device CodeTVs, CLI tools
Refresh TokenRenew access tokens
Implicit DEPRECATEDReplaced by Auth Code + PKCE
Password DEPRECATEDReplaced 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

ComponentNotes
Session cookieSet-Cookie: sid=...; HttpOnly; Secure; SameSite=Lax
Server storeRedis, DB, in-memory
CSRF protectionRequired (token, SameSite, custom header)
Use caseBrowser-only apps with same-origin API

7. Implementing Multi-Factor Authentication

FactorMethod
TOTPGoogle Authenticator, Authy (RFC 6238)
SMSCode via text (weak — SIM-swap risk)
WebAuthn / Passkeys NEWPhishing-resistant, hardware-backed
Push notificationApprove in companion app
Email magic linkPassword-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 PracticeReason
Rotate refresh tokensDetect token theft
Detect reuse → revoke familyReplay attack mitigation
Long-lived (days/weeks)Access tokens stay short-lived (15-60 min)

9. Implementing Token Expiration

TokenTypical Lifetime
Access token15-60 minutes
Refresh token7-90 days
ID tokenSame as access
API key (long-lived)Months/years; rotate periodically

10. Securing Authentication Endpoints

ProtectionImplementation
Rate limitingPer IP + per username
Account lockoutAfter N failed attempts
CAPTCHAAfter threshold
Generic error"Invalid credentials" — not "user exists"
Constant-time comparisonPrevent timing attacks
LoggingAll auth attempts (no passwords)

11. Handling Authentication Errors

StatusCauseWWW-Authenticate
401Missing/invalid/expired tokenBearer realm="api", error="invalid_token"
401Token expirederror="invalid_token", error_description="expired"
403Token valid but lacks scopeerror="insufficient_scope", scope="orders:write"