API Authentication Design Template
Template for documenting API authentication: scheme selection, token lifecycle, JWT config, OAuth2 flows, refresh, revocation, MFA, and security best practices.
Overview
This template captures the authentication design for an API — scheme selection, token types, issuance, validation, refresh, revocation, MFA, and the security checklist that goes with them. Fill it in when designing auth for a new API, or use it as a review checklist on one that already exists.
How to Use This Template
Work the sections in order — the answers compound. Section 1 pins the scheme; everything after that assumes it. Section 2 decides how long tokens live and where they sit; that choice determines what Sections 5 and 6 (refresh and revocation) have to handle. Sections 3 and 4 are where the JWT claims and OAuth2 flows get written down concretely, not left as “we use JWT”.
When reviewing an existing API instead of designing one, read the template backwards: start at the Section 7 checklist, mark every box that fails, and trace each failure back to the section that should have decided it. An access token living in localStorage is a Section 2 failure; a missing jti is Section 3; refresh tokens that never rotate is Section 5.
Two things make the filled template reviewable rather than aspirational: every choice gets a concrete value (a TTL, an algorithm, an endpoint) and every “it depends” gets the dependency named — “mTLS when inside the mesh, JWT at the edge” is a decision; “mTLS or JWT” is not. Pair it with the API security review template when the output needs a second pair of eyes.
1. Auth Scheme Selection
1.1 Scheme Comparison
Scheme | Best for | Token lifetime | State
────────────────────┼─────────────────────────────┼────────────────┼──────────
Bearer JWT | Stateless APIs, microservices| Short (15min) | Stateless
Opaque token | Stateful APIs, web apps | Medium (1h) | Stateful
API key | Service-to-service, dev | Long (90d) | Stateful
OAuth2 access token | Third-party access | Short (1h) | Varies
mTLS | Service mesh, zero-trust | Connection | Stateless
1.2 Decision Matrix
Requirement | Recommended scheme
───────────────────────────┼──────────────────────────────
Stateless microservices | Bearer JWT (RS256)
Web application (SSR) | Opaque token + session cookie
Mobile app | OAuth2 + PKCE + refresh token
Service-to-service | mTLS or API key
Third-party integration | OAuth2 client credentials
Machine-to-machine | OAuth2 client credentials
Legacy system | API key (with IP allowlist)
High-security (banking) | mTLS + JWT + MFA
2. Token Lifecycle
2.1 Token Types
Token type | Purpose | Lifetime | Storage
───────────────────┼──────────────────────┼─────────────┼──────────────────────
Access token | API authorization | 15 min | Memory (client-side)
Refresh token | Get new access token | 7-30 days | HttpOnly cookie / secure
ID token | User identity (OIDC) | 15 min | Memory (client-side)
API key | Service auth | 90 days | Secrets manager
Session token | Web session | 30 min idle | Server-side store
2.2 Lifecycle Diagram
1. User authenticates (username/password + MFA)
│
▼
2. Server validates credentials
│
▼
3. Server issues access token (JWT) + refresh token
│
├── Access token → client memory (never localStorage)
└── Refresh token → HttpOnly, Secure, SameSite=Strict cookie
│
▼
4. Client sends access token in Authorization header
│
▼
5. Server validates token (signature, expiry, issuer, audience)
│
▼
6. Access token expires → client sends refresh token
│
▼
7. Server validates refresh token → issues new access token
│
▼
8. User logs out → server revokes refresh token
│
▼
9. Refresh token expires or revoked → user must re-authenticate
3. JWT Configuration
3.1 JWT Structure
Header:
{
"alg": "RS256", # Signing algorithm (never none or HS256 for distributed)
"typ": "JWT",
"kid": "key-v2" # Key ID for key rotation
}
Payload (claims):
{
"iss": "https://auth.example.com", # Issuer
"sub": "user-12345", # Subject (user ID)
"aud": ["api.example.com"], # Audience
"exp": 1719900000, # Expiration (Unix timestamp)
"iat": 1719899100, # Issued at
"nbf": 1719899100, # Not before
"jti": "token-uuid-123", # JWT ID (for revocation)
"scope": "read:orders write:orders", # Scopes/permissions
"roles": ["user", "customer"],
"ip": "192.168.1.100" # Binding (optional)
}
Signature:
RS256(header + "." + payload, private_key)
3.2 JWT Issuance (Python)
import jwt
from datetime import datetime, timedelta, timezone
from cryptography.hazmat.primitives import serialization
def issue_access_token(user_id: str, scopes: list[str]) -> str:
private_key = load_private_key() # From secrets manager
now = datetime.now(timezone.utc)
payload = {
'iss': 'https://auth.example.com',
'sub': user_id,
'aud': ['api.example.com'],
'exp': now + timedelta(minutes=15),
'iat': now,
'nbf': now,
'jti': str(uuid.uuid4()),
'scope': ' '.join(scopes),
}
return jwt.encode(
payload,
private_key,
algorithm='RS256',
headers={'kid': 'key-v2'},
)
def issue_refresh_token(user_id: str) -> str:
# Refresh token is opaque (not JWT) — stored server-side
token = secrets.token_urlsafe(48)
store_refresh_token(token, user_id, expires_in=timedelta(days=7))
return token
3.3 JWT Validation (Python)
import jwt
from jwt import PyJWKClient
# Fetch public keys from JWKS endpoint
jwks_client = PyJWKClient('https://auth.example.com/.well-known/jwks.json')
def validate_access_token(token: str) -> dict:
try:
signing_key = jwks_client.get_signing_key_from_jwt(token)
payload = jwt.decode(
token,
signing_key.key,
algorithms=['RS256'],
audience='api.example.com',
issuer='https://auth.example.com',
options={
'verify_exp': True,
'verify_iat': True,
'verify_aud': True,
'verify_iss': True,
},
)
return payload
except jwt.ExpiredSignatureError:
raise AuthError('Token expired')
except jwt.InvalidAudienceError:
raise AuthError('Invalid audience')
except jwt.InvalidIssuerError:
raise AuthError('Invalid issuer')
except jwt.InvalidTokenError:
raise AuthError('Invalid token')
4. OAuth2 Flows
4.1 Flow Selection
Flow | Use case | Token returned via
────────────────────────┼─────────────────────────────┼──────────────────────
Authorization Code | Web app (server-side) | Code exchange
Authorization Code + PKCE| Mobile / SPA | Code exchange + verifier
Client Credentials | Service-to-service | Direct (no user)
Resource Owner Password | Legacy (not recommended) | Direct
Device Code | TV, IoT, CLI | Device polling
Implicit | DEPRECATED | URL fragment
Implicit is gone — the OAuth 2.0 Security Best Current Practice (RFC 9700) retires it in favor of Authorization Code + PKCE, and Resource Owner Password Credentials survives only for first-party legacy clients that can’t do a redirect.
4.2 Authorization Code + PKCE (SPA/Mobile)
// Step 1: Generate PKCE verifier and challenge
const verifier = generateRandomString(64);
const challenge = await sha256(verifier).then(base64urlEncode);
const state = generateRandomString(32);
// Step 2: Redirect to authorization endpoint
const authUrl = new URL('https://auth.example.com/authorize');
authUrl.searchParams.set('response_type', 'code');
authUrl.searchParams.set('client_id', 'my-client-id');
authUrl.searchParams.set('redirect_uri', 'https://app.example.com/callback');
authUrl.searchParams.set('scope', 'openid profile read:orders');
authUrl.searchParams.set('state', state);
authUrl.searchParams.set('code_challenge', challenge);
authUrl.searchParams.set('code_challenge_method', 'S256');
window.location.href = authUrl.toString();
// Step 3: Exchange code for tokens (in callback)
const response = await fetch('https://auth.example.com/token', {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams({
grant_type: 'authorization_code',
client_id: 'my-client-id',
code: authCode,
redirect_uri: 'https://app.example.com/callback',
code_verifier: verifier, // PKCE verifier from step 1
}),
});
const { access_token, refresh_token, id_token, expires_in } = await response.json();
4.3 Client Credentials (Service-to-Service)
import requests
def get_service_token() -> str:
response = requests.post('https://auth.example.com/token', data={
'grant_type': 'client_credentials',
'client_id': 'payment-service',
'client_secret': get_secret('payment-service-secret'),
'scope': 'read:orders write:orders',
})
token_data = response.json()
return token_data['access_token']
5. Token Refresh
5.1 Refresh Flow
from flask import request, response, jsonify
@app.route('/auth/refresh', methods=['POST'])
def refresh_token():
refresh_token = request.cookies.get('refresh_token')
if not refresh_token:
return jsonify({'error': 'no refresh token'}), 401
# Validate refresh token server-side
stored = get_refresh_token(refresh_token)
if not stored or stored.is_expired() or stored.is_revoked():
return jsonify({'error': 'invalid refresh token'}), 401
# Check token rotation — old token should be invalidated
if stored.used:
# Possible token theft — revoke all tokens for this user
revoke_all_tokens(stored.user_id)
return jsonify({'error': 'token reuse detected'}), 401
# Issue new access token
new_access = issue_access_token(stored.user_id, stored.scopes)
# Rotate refresh token (issue new, revoke old)
new_refresh = issue_refresh_token(stored.user_id)
revoke_refresh_token(refresh_token)
resp = jsonify({'access_token': new_access})
resp.set_cookie(
'refresh_token',
new_refresh,
httponly=True,
secure=True,
samesite='Strict',
max_age=7 * 24 * 3600,
path='/auth/refresh',
)
return resp
6. Token Revocation
6.1 Revocation Strategies
Strategy | How it works | Tradeoff
──────────────────────┼────────────────────────────────────┼──────────────────────
Short expiry | Token expires in 15 min | Frequent refresh
Blocklist (jti) | Store revoked jti in Redis | Stateful, check on every request
Token versioning | User has token_version, increment | Invalidates all tokens at once
Refresh token revoke | Revoke refresh, access expires soon| Delayed revocation
Session destroy | Delete server-side session | Immediate for session tokens
6.2 Blocklist Implementation
import redis
import time
r = redis.Redis(host='redis', port=6379, db=0)
def revoke_token(jti: str, exp: int):
# Store jti in Redis with TTL matching token expiry
ttl = exp - int(time.time())
if ttl > 0:
r.setex(f'revoked:{jti}', ttl, '1')
def is_token_revoked(jti: str) -> bool:
return r.exists(f'revoked:{jti}') > 0
# In token validation
def validate_access_token(token: str) -> dict:
payload = decode_jwt(token)
if is_token_revoked(payload['jti']):
raise AuthError('Token revoked')
return payload
7. Security Best Practices
- For a deeper guide, see OAuth2 and OIDC: Authorization Code, PKCE, Token Validation.
7.1 Checklist
Token storage:
- [ ] Access tokens in memory only (never localStorage)
- [ ] Refresh tokens in HttpOnly, Secure, SameSite cookie
- [ ] Never store tokens in URL parameters
- [ ] Clear tokens on logout
Token configuration:
- [ ] Access token TTL: 15 minutes
- [ ] Refresh token TTL: 7-30 days
- [ ] Use RS256 or ES256 (asymmetric) for JWT signing
- [ ] Never use 'none' algorithm
- [ ] Set issuer, audience, and verify on validation
- [ ] Include jti for revocation support
- [ ] Rotate signing keys regularly
Transport security:
- [ ] All token exchange over HTTPS only
- [ ] Set HSTS header
- [ ] Reject non-HTTPS redirects
Attack prevention:
- [ ] Implement rate limiting on auth endpoints
- [ ] Account lockout after failed attempts
- [ ] CSRF protection on cookie-based endpoints
- [ ] PKCE for all public clients (SPA, mobile)
- [ ] Validate redirect_uri against allowlist
- [ ] Use state parameter to prevent CSRF in OAuth2
- [ ] Implement token rotation for refresh tokens
- [ ] Detect refresh token reuse (revoke all on reuse)
8. Multi-Factor Authentication
MFA gates issuance, not every request — the factor challenge happens once, when credentials are presented, and the resulting token carries the proof. The design decisions to write down:
Factor | Strength | Notes
────────────────────┼───────────┼──────────────────────────────────────────
WebAuthn / FIDO2 | Strongest | Hardware key or biometrics; phishing-resistant
TOTP | Strong | 6-digit code; RFC 6238; encrypt seed at rest
Push approval | Strong | Number-matching preferred over approve/deny
SMS OTP | Weak | SIM-swapping exposure; acceptable only as fallback
Recovery codes | Fallback | Single-use, hashed at rest, rate-limited
Fill in for the API: which factors enroll, which is default, and which operations demand step-up — a fresh factor check even with a valid token. Password change, payout, scope elevation, and token export are the usual step-up set. The issued token records the assurance: an mfa_verified: true claim (or ACR claim in OIDC terms) lets resource servers distinguish first-factor sessions from fully-verified ones, and the step-up path re-issues or re-checks rather than trusting a stale claim.
9. Token Error Responses
Standardize what clients see when a token fails. Undifferentiated 401s teach clients to retry; precise errors let them recover correctly — refresh once, re-authenticate, or stop.
Condition | HTTP | error code | Client action
─────────────────────────────┼──────┼───────────────────────┼──────────────────────────
Missing Authorization header | 401 | unauthorized | Authenticate first
Expired access token | 401 | invalid_token | Refresh once, then re-auth
Revoked token (jti hit) | 401 | invalid_token | Re-authenticate
Bad signature / malformed | 401 | invalid_token | Re-authenticate
Wrong issuer or audience | 401 | invalid_token | Config bug — do not retry
Insufficient scope | 403 | insufficient_scope | Request higher scope
Refresh token reuse detected | 401 | invalid_grant | Re-authenticate; all tokens revoked
Rate limited | 429 | rate_limited | Back off, Retry-After
Two rules keep this honest. Respond with the WWW-Authenticate header the way RFC 6750 prescribes — Bearer realm="api", error="invalid_token", error_description="..." — so standards-aware clients parse the failure instead of string-matching the body. And never echo the rejected token, the expected signature, or internal details (“key key-v2 not found”) in the response; log those server-side with the jti for forensics.
10. Operational Notes
Small operational choices bite later if they aren’t written down:
- Clock skew: allow 30-60 seconds of leeway on
exp/nbfvalidation; distributed systems drift, and a hard zero-skew check produces flaky 401s. - Key rotation cadence: publish a JWKS endpoint, rotate signing keys on a schedule (quarterly is a sane default), and keep the previous
kidverifiable until the longest-lived token signed with it could have expired — with 15-minute access tokens, one overlap window is enough. - Refresh cookie scoping: bind the refresh cookie to
path=/auth/refreshso it never leaves the browser on ordinary API calls. - Blocklist TTL: size the Redis TTL to the remaining token lifetime, never longer — a forever-entry is a slow leak.
- Clock for logs: log
jti,sub,issand a hash of the token, not the token itself; logs are a leak vector. - Secret storage: the signing private key and client secrets live in a secrets manager, never in env vars committed with the deploy or in the codebase; rotation happens there, not in application config, and access is scoped to the service that needs it.
11. Customizing the Template
Not every API needs every row of this template, and a half-empty section filled with boilerplate is worse than a short decisive one. The minimum viable document is Sections 1, 2, 3 and 7 — scheme, lifetimes, claims, checklist. Sections 4-6 matter only when refresh or third-party flows exist; a pure API-key service can collapse them into one line (“no OAuth2; keys issued out-of-band”).
Adapt the tables, don’t append beside them. If the service uses opaque tokens instead of JWTs, rewrite Section 3 rather than adding “N/A” — a section that says “tokens are opaque, validated by introspection against auth-db, caching 60s” is a decision record; “N/A” is a hole. The same goes for MFA: an internal service behind mTLS documents “no end-user MFA — workload identity only” in Section 8 and moves on.
Two extension points teams commonly bolt on: a per-endpoint scope matrix (which scopes can call which routes — security review will ask for it anyway) and a threat-model link for anything touching money, PII, or admin actions. Keep both out of the template body and link them; the template stays a one-page decision record, not the security design doc.
Revisit the filled template on two triggers: when the auth stack changes (new IdP, new flow, new signing key scheme) and on a fixed cadence — a template last touched two years ago is describing a system that no longer exists. Date each section’s lastUpdated or fold that into the review checklist.
The template earns its keep in the arguments it ends. “Should refresh tokens rotate?” is a design review that takes twenty minutes without a written policy and two minutes with one — the answer was already decided and recorded. Write the decision where the next reviewer looks for it: in the section that owns it, with the value that was chosen.
Further Reading
- OAuth 2.0 RFC 6749 — the authorization framework
- OWASP — API Security — the threat list
- JWT.io — the token debugger and spec reference
Frequently Asked Questions
Should I use JWT or opaque tokens?
Reach for JWT on stateless APIs — the claims ride inside the token, so a signature check replaces a database lookup per request. Reach for opaque tokens when you need instant revocation or real session management — a random string looked up server-side gives you that, and the client never sees the contents. Microservices lean JWT; single-server apps lean opaque. Mixing works too: short-lived JWT for access, opaque token for refresh.
How do I revoke a JWT before it expires?
JWTs don't know they've been revoked — they're valid until expiry by design. The standard fix is a blocklist: write revoked jti values into Redis with a TTL matching the remaining token life, and check it per request. That buys revocation at the cost of one lookup. If you'd rather skip Redis, keep access tokens at 5-15 minutes and revoke the refresh token instead — the access token dies on its own. For a kill-switch, bump a token_version on the user record and put it in the claim: old-version tokens get rejected everywhere.
What is PKCE and why do I need it?
PKCE (Proof Key for Code Exchange) stops authorization code interception. The client hashes a random code verifier into a code challenge and sends that with the auth request; on token exchange it sends the raw verifier, and the server checks the pair. That proves whoever redeems the code is whoever started the flow. Public clients (SPAs, mobile apps) can't hold a secret, so PKCE is mandatory there — and on confidential clients it's cheap defense in depth anyway.
How should I store tokens on the client side?
Keep access tokens in memory — a JS variable — since they're short-lived anyway. Refresh tokens go in an HttpOnly, Secure, SameSite=Strict cookie: JavaScript can't read them (XSS), they don't ride cross-site requests (CSRF). localStorage and sessionStorage are both readable by any script on the page — don't use them for tokens. URLs are worse: tokens in query params end up in proxy and browser logs. On mobile, use the platform's secure store — Keychain on iOS, Keystore on Android.
How do I implement MFA in my authentication flow?
Validate username and password first, then gate token issuance on a second factor. The menu: TOTP (Google Authenticator, Authy) — a 6-digit code; SMS OTP — works but exposes you to SIM swapping; WebAuthn/FIDO2 — hardware key or biometrics, the strongest option; push — approve on the user's phone. Once the factor passes, issue tokens with an mfa_verified: true claim, and re-verify for sensitive operations (password change, money transfer) even when the claim is there. Store enrollment data — TOTP secrets, device tokens — encrypted at rest.
Related Resources
OWASP Top 10 Remediation Checklist
Checklist for tracking OWASP Top 10 vulnerability remediation per application: risk assessment, fix priority, code-level remediation steps, verification testing, and compliance reporting with examples for each OWASP category.
DocSecrets Rotation Runbook
Runbook for rotating secrets without downtime: secret inventory, dual-key rotation, AWS Secrets Manager, HashiCorp Vault, JWT keys and emergency procedures.
DocSecurity Review Checklist for PRs
Checklist for security checks during pull request review: input validation, authentication, authorization, secrets, dependencies, injection, XSS, CSRF, logging, and automated tooling integration with code examples for secure patterns.
DocAPI Security Review Template (OWASP Checklist)
A fillable checklist template for reviewing API authentication, authorization, rate limiting, and OWASP API Security Top 10 coverage.
GuideOAuth2 and OIDC: Authorization Code, PKCE, Token Validation
Implement OAuth2 and OIDC in production: PKCE authorization code flow, JWKS token validation, refresh token rotation, revocation, and secure token storage.
RecipeSecure API Key Authentication for Services and Clients
How to generate, distribute, validate, and rotate API keys for machine-to-machine authentication using HMAC signatures, scopes, and rate-limited key policies.