Working with API Authentication

1. Implementing API Keys

AspectDetail
FormatRandom 32+ bytes, base62/base64url
Prefixsk_live_, pk_test_ for grep/leak detection
StorageSHA-256 hashed in DB
DisplayShow once at creation

2. Implementing API Key Rotation

StepDetail
Dual keysAllow two active keys per service
Issue newUpdate consumer; both valid
Revoke oldAfter cutover window
Schedule90-day rotation

3. Using OAuth 2.0 for APIs

GrantUse
Client credentialsM2M
Authorization code + PKCEUser-delegated
JWT bearerTrusted client assertion
Token exchangeService-to-service with user context

4. Implementing Bearer Authentication

Example: Spring Resource Server

http.oauth2ResourceServer(o -> o.jwt(j ->
  j.jwkSetUri("https://auth.example/.well-known/jwks.json")));

5. Using Basic Authentication for APIs

WhenDetail
AcceptableInternal admin, M2M behind VPN
AvoidPublic APIs, mobile/web
Pair withIP allowlist, mTLS

6. Implementing Digest Authentication

Rarely used in modern APIs. Replace with Bearer/HMAC.

7. Using Mutual TLS

AspectDetail
SetupServer requires/verifies client cert
PKIInternal CA, short-lived certs (SPIFFE/SPIRE)
MeshIstio/Linkerd handle automatically

8. Implementing HMAC Signatures

Example: HMAC-SHA256 signing

const ts = Date.now();
const body = JSON.stringify(payload);
const sig = crypto.createHmac("sha256", secret)
  .update(`${method}\n${path}\n${ts}\n${body}`).digest("base64");

headers["X-Timestamp"] = ts;
headers["X-Signature"] = sig;

9. Using AWS Signature V4

StepDetail
Canonical requestMETHOD + URI + query + headers + payload-hash
String to signalgorithm + date + scope + sha256(canonical)
Signing keyHMAC chain: secret → date → region → service → "aws4_request"
HeaderAuthorization: AWS4-HMAC-SHA256 Credential=...,Signature=...

10. Implementing Rate Limiting by Identity

KeyDetail
By API keyTier-based quotas
By userAuthenticated user limits
By IPFallback for anonymous
Response429 + Retry-After, X-RateLimit-* headers

11. Handling Authentication Errors

CodeUse
401Missing/invalid credentials
403Authenticated but insufficient scope/permission
429Rate limit exceeded
BodyRFC 7807 problem+json; never reveal internals