The first time I shipped an OAuth flow to production, I lost two days to a single character in a redirect_uri. Trailing slash. The auth server rejected every callback with invalid_redirect_uri and the error message was, charitably, "no." That was the day I learned that authentication code is the only place in software where "it works on my machine" can take down a Fortune-500 customer's login.
Here's the truth about OAuth and JWT that most tutorials skip: the spec is the easy part. The hard part is every trade-off you make afterward-where to store tokens, how long they live, who rotates what, what happens when a key leaks. Get those wrong and you'll be the next "we leaked 200M user tokens" headline. Get them right and auth stops being a thing you think about, which is the goal.
This is the guide I wish someone had handed me in 2019. We're going to build a real authorization server with the authorization-code-with-PKCE flow, RS256-signed JWTs, refresh-token rotation, and a protected resource API that actually validates everything. Then we'll talk about every way I've seen teams break this in production.
Why OAuth Exists and Why You Shouldn't Roll Your Own
Quick context. Before OAuth 2.0, if you wanted app A to act on behalf of user B against service C, you handed app A the user's password. That meant app A stored the password, could do anything the user could do, and you had no way to revoke just that app without nuking the user's account.
OAuth 2.0 (RFC 6749, 2012) fixed this with delegated authorization: the user authenticates once with the authorization server, the server issues a scoped, revocable access token, and the app never sees the password. JWT (RFC 7519) is a token format-JSON claims, base64-encoded, signed-often used as the access token. The two are not the same thing. OAuth is a framework; JWT is a serialization. You can do OAuth without JWT (opaque tokens looked up in a DB), and you can use JWT without OAuth (session tokens). Most modern stacks combine them.
Don't roll your own crypto, don't roll your own auth protocol, and absolutely don't invent a fourth flow "because it's simpler." Use a library. Use a managed provider if you can afford one. The code below is illustrative of how the pieces fit, but for anything that touches real users, pick Auth0, Clerk, WorkOS, Keycloak, or your cloud's identity product and let them handle the edges.
The Flow You Should Almost Always Use: Authorization Code with PKCE
There are five OAuth 2.0 flows in the original RFC, plus a couple added later. Most of them you should never use in 2024. Here's the decision tree:
| Flow | Use case | Should you use it? |
|---|---|---|
| Authorization Code + PKCE | Browser apps, SPAs, mobile, desktop | Yes-this is the modern default |
| Client Credentials | Server-to-server, machine-to-machine | Yes |
| Refresh Token | Renewing an expired access token | Yes |
| Implicit | Old SPAs without backend | No-deprecated in OAuth 2.1 |
| Password (ROPC) | First-party trusted apps | No-deprecated, dangerous |
| Device Code | TVs, IoT, CLI tools with no browser | Yes for those specific cases |
Authorization Code with PKCE (Proof Key for Code Exchange, RFC 7636) is what you want for almost everything user-facing. The flow:
CodeCopy +--------+ +---------------+
| |--(A) Authorization Request---->| Resource |
| User | | Owner |
| Agent |<-(B) User authenticates--------| (user clicks |
| (browser| | "approve") |
| | +---------------+
| | +---------------+
| |--(C) Code + state redirect---->| |
| | | Authorization |
| |--(D) Code + verifier POST----->| Server |
| |<-(E) Access Token + Refresh----| |
+--------+ +---------------+
|
v
+---------------+
| Resource |
| Server/API |
+---------------+
The PKCE bit is critical: the client generates a random code_verifier (43-128 chars), hashes it to a code_challenge, sends the challenge in step A, and proves it has the original verifier in step D. This prevents an attacker who intercepts the authorization code (e.g., a malicious app on the same device registering a custom URL scheme) from exchanging it for a token. SPAs and mobile apps MUST use PKCE. No exceptions. OAuth 2.1 makes PKCE mandatory for all flows for exactly this reason.
Architecture Overview
We're building three pieces:
- Authorization Server (AS) - issues tokens, manages consent, handles login. This is what most teams buy from a vendor.
- Resource Server (RS) - your API. It validates tokens and enforces scopes.
- Client - your frontend app. It drives the flow and stores tokens.
Folder structure for the demo:
CodeCopy
plaintext
auth-demo/
├── package.json
├── .env
├── keys/
│ ├── private.pem # RS256 private key (NEVER commit)
│ └── public.pem # RS256 public key (safe to share)
├── src/
│ ├── auth-server.js # Authorization server (Express)
│ ├── resource-server.js # Protected API (Express)
│ ├── jwt-utils.js # Sign/verify/decode helpers
│ ├── pkce.js # PKCE verifier/challenge helpers
│ └── store.js # In-memory store (replace with Redis in prod)
└── public/
└── client.html # Tiny SPA that drives the flow
markdown
In production, the AS and RS are usually separate services, often in separate repos. The keys directory is a stand-in for a KMS-backed key store; never literally check private.pem into git, and never read it from disk in a serverless function cold-start path-use a secret manager.
Prerequisites and Environment Setup
You need Node 20+ (we'll use native fetch and Web Crypto), a recent npm, and OpenSSL for key generation.
BashCopy
shell
mkdir auth-demo && cd auth-demo
npm init -y
npm install express@4.19.2 cookie-parser@1.4.6 cors@2.8.5 helmet@7.1.0 jose@5.6.3 nanoid@5.0.7 dotenv@16.4.5
npm install -D nodemon@3.1.4
plaintext
Why jose and not jsonwebtoken? jose is maintained, supports JWKS (key rotation via a public keyset endpoint), and runs on Web Crypto so it works in workers and edge runtimes. jsonwebtoken is fine for simple cases but has had CVEs around algorithm confusion and is essentially in maintenance mode.
Generate an RSA keypair for RS256 signing:
BashCopy
shell
mkdir -p keys
openssl genpkey -algorithm RSA -out keys/private.pem -pkeyopt rsa_keygen_bits:2048
openssl rsa -in keys/private.pem -pubout -out keys/public.pem
chmod 600 keys/private.pem
plaintext
Add .env:
BashCopy
conf
PORT_AUTH=4000
PORT_API=4100
ISSUER=http://localhost:4000
ACCESS_TOKEN_TTL=900 # 15 minutes
REFRESH_TOKEN_TTL=2592000 # 30 days
KEY_ID=demo-key-1
plaintext
Add .gitignore:
CodeCopy
plaintext
node_modules/
.env
keys/private.pem
markdown
I have seen the keys/private.pem in a public GitHub repo exactly once, in 2021, and it was a fintech. They reissued every user session in 4 hours and got lucky nothing worse happened. Don't be that team.
JWT Structure, Signing Algorithms, and Why HS256 Is a Footgun
A JWT is three base64url segments separated by dots: header.payload.signature. The header says what algorithm and key id. The payload is your claims. The signature is the header+payload signed with the key.
Standard claims you should care about: iss (issuer), sub (subject, the user id), aud (audience, who the token is for), exp (expiry), iat (issued at), nbf (not before), jti (unique token id for revocation), scope (space-delimited permission string).
Now the algorithm question. Two common choices:
- HS256 - HMAC with SHA-256. Symmetric. Same key signs and verifies. Simple, fast, but every service that validates a token has the signing key, which means any of them can forge tokens.
- RS256 - RSA signature with SHA-256. Asymmetric. Private key signs, public key verifies. Resource servers only need the public key. Compromise of a verifier doesn't let you forge tokens.
| Aspect | HS256 | RS256 |
|---|---|---|
| Key type | Symmetric (shared secret) | Asymmetric (RSA keypair) |
| Who can sign | Anyone with the key | Only the AS (private key) |
| Who can verify | Anyone with the key | Anyone with the public key |
| Key rotation | Harder-everyone needs the new secret | Easier-publish new JWKS, verify both for a window |
| Token size | Smaller (~200 bytes) | Larger (~800 bytes for 2048-bit RSA) |
| Common footgun | Secret leaks via resource server | Slower signing (negligible for most workloads) |
Default to RS256 in any multi-service setup. HS256 is fine if you have exactly one service that both signs and validates, and even then, RS256 is barely more code.
There's also ES256 (ECDSA P-256). Same security as RS256 with much smaller signatures (~64 bytes vs ~256). The catch is implementation landmines around signature malleability-use a vetted library (jose handles this) and you're fine. ES256 is a great choice if you care about token size or are in a mobile environment.
Implementation: PKCE Helpers and JWT Utilities
src/pkce.js:
JavaScriptCopy
javascript
// PKCE helpers using Web Crypto (Node 20+ has it global)
export function base64url(bytes) {
return Buffer.from(bytes).toString('base64')
.replace(/+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
}
export function generateCodeVerifier() {
// 32 random bytes -> 43 char base64url string (minimum allowed length)
const bytes = new Uint8Array(32);
crypto.getRandomValues(bytes);
return base64url(bytes);
}
export function computeCodeChallenge(verifier) {
// SHA-256(verifier), base64url-encoded
const data = new TextEncoder().encode(verifier);
return crypto.subtle.digest('SHA-256', data).then(base64url);
}
plaintext
src/jwt-utils.js:
JavaScriptCopy
javascript
import { SignJWT, jwtVerify, createRemoteJWKSet } from 'jose';
import { readFileSync } from 'node:fs';
import path from 'node:path';
const PRIVATE_KEY = readFileSync(path.join(process.cwd(), 'keys/private.pem'), 'utf8');
const PUBLIC_KEY = readFileSync(path.join(process.cwd(), 'keys/public.pem'), 'utf8');
const KEY_ID = process.env.KEY_ID;
const ISSUER = process.env.ISSUER;
export async function signAccessToken({ sub, scope, audience }) {
return new SignJWT({ scope })
.setProtectedHeader({ alg: 'RS256', kid: KEY_ID })
.setIssuer(ISSUER)
.setSubject(sub)
.setAudience(audience)
.setIssuedAt()
.setExpirationTime(${process.env.ACCESS_TOKEN_TTL}s)
.setJti(crypto.randomUUID())
.sign(PRIVATE_KEY);
}
export async function signRefreshToken({ sub, scope, audience, jti }) {
return new SignJWT({ scope, jti })
.setProtectedHeader({ alg: 'RS256', kid: KEY_ID })
.setIssuer(ISSUER)
.setSubject(sub)
.setAudience(audience)
.setIssuedAt()
.setExpirationTime(${process.env.REFRESH_TOKEN_TTL}s)
.sign(PRIVATE_KEY);
}
export async function verifyToken(token, expectedAudience) {
const { payload } = await jwtVerify(token, PUBLIC_KEY, {
issuer: ISSUER,
audience: expectedAudience,
algorithms: ['RS256'], // CRITICAL: pin the algorithm
});
return payload;
}
markdown
That algorithms: ['RS256'] line is the most important line in this whole file. Without it, you're vulnerable to the classic algorithm-confusion attack: an attacker takes a public RS256 key, submits it as an HMAC secret, and your verifier happily accepts HS256-forged tokens because it auto-detects the algorithm from the header. Pin the algorithm. Always.
Implementation: The Authorization Server
src/auth-server.js - a complete (if minimal) authorization server implementing authorization-code-with-PKCE, the token endpoint with refresh rotation, and a JWKS endpoint:
JavaScriptCopy
javascript
import express from 'express';
import cookieParser from 'cookie-parser';
import helmet from 'helmet';
import cors from 'cors';
import { nanoid } from 'nanoid';
import dotenv from 'dotenv';
import { generateCodeVerifier, computeCodeChallenge } from './pkce.js';
import { signAccessToken, signRefreshToken, verifyToken } from './jwt-utils.js';
dotenv.config();
const app = express();
app.use(helmet());
app.use(cookieParser());
app.use(express.urlencoded({ extended: false }));
app.use(express.json());
app.use(cors({ origin: 'http://localhost:5173', credentials: true }));
// In-memory stores. Replace with Redis in production.
const codes = new Map(); // code -> { sub, scope, code_challenge, redirect_uri, used }
const refreshTokens = new Map(); // jti -> { sub, scope, audience, used }
const CLIENTS = {
'demo-spa': {
redirect_uris: ['http://localhost:5173/callback'],
token_endpoint_auth_method: 'none', // public client, no secret
},
};
// --- Authorization endpoint ---
app.get('/authorize', async (req, res) => {
const {
response_type, client_id, redirect_uri,
scope, state, code_challenge, code_challenge_method, nonce,
} = req.query;
// 1. Validate request
if (response_type !== 'code') return res.status(400).send('unsupported_response_type');
const client = CLIENTS[client_id];
if (!client) return res.status(400).send('unauthorized_client');
if (!client.redirect_uris.includes(redirect_uri)) {
return res.status(400).send('invalid_redirect_uri'); // <-- the trailing-slash villain
}
if (!code_challenge || code_challenge_method !== 'S256') {
return res.status(400).send('pkce_required');
}
// 2. In a real AS, here you'd redirect to a login page / consent screen.
// For the demo, assume user_id is in a session cookie or default to "demo-user".
const userId = req.cookies.session_user || 'user_123';
// 3. Issue an authorization code, store the challenge
const code = nanoid(32);
codes.set(code, {
sub: userId,
scope: scope || 'read',
code_challenge,
redirect_uri,
client_id,
expires_at: Date.now() + 60_000, // codes live 60s
used: false,
});
// 4. Redirect back to client with code+state
const url = new URL(redirect_uri);
url.searchParams.set('code', code);
if (state) url.searchParams.set('state', state);
res.redirect(url.toString());
});
// --- Token endpoint ---
app.post('/token', async (req, res) => {
const { grant_type } = req.body;
if (grant_type === 'authorization_code') {
const { code, redirect_uri, client_id, code_verifier } = req.body;
const entry = codes.get(code);
if (!entry || entry.used) return res.status(400).json({ error: 'invalid_grant' });
if (Date.now() > entry.expires_at) return res.status(400).json({ error: 'invalid_grant' });
if (entry.client_id !== client_id) return res.status(400).json({ error: 'invalid_client' });
if (entry.redirect_uri !== redirect_uri) return res.status(400).json({ error: 'invalid_grant' });
// Verify PKCE
const expectedChallenge = await computeCodeChallenge(code_verifier);
if (expectedChallenge !== entry.code_challenge) {
return res.status(400).json({ error: 'invalid_grant', error_description: 'pkce_failed' });
}
entry.used = true;
codes.delete(code);
const access = await signAccessToken({
sub: entry.sub, scope: entry.scope, audience: 'api://demo',
});
const jti = nanoid(32);
const refresh = await signRefreshToken({
sub: entry.sub, scope: entry.scope, audience: 'api://demo', jti,
});
refreshTokens.set(jti, {
sub: entry.sub, scope: entry.scope, audience: 'api://demo',
used: false, rotated_from: null,
});
return res.json({
access_token: access,
refresh_token: refresh,
token_type: 'Bearer',
expires_in: parseInt(process.env.ACCESS_TOKEN_TTL, 10),
scope: entry.scope,
});
}
if (grant_type === 'refresh_token') {
const { refresh_token, client_id } = req.body;
let payload;
try {
payload = await verifyToken(refresh_token, 'api://demo');
} catch {
return res.status(400).json({ error: 'invalid_grant' });
}
const stored = refreshTokens.get(payload.jti);
if (!stored) return res.status(400).json({ error: 'invalid_grant' });
if (stored.used) {
// REFRESH TOKEN REUSE DETECTION - token has been replayed, kill the family
refreshTokens.forEach((v, k) => { if (v.sub === stored.sub) refreshTokens.delete(k); });
return res.status(400).json({ error: 'invalid_grant', error_description: 'reuse_detected' });
}
stored.used = true;
const access = await signAccessToken({
sub: stored.sub, scope: stored.scope, audience: 'api://demo',
});
const newJti = nanoid(32);
const newRefresh = await signRefreshToken({
sub: stored.sub, scope: stored.scope, audience: 'api://demo', jti: newJti,
});
refreshTokens.set(newJti, {
sub: stored.sub, scope: stored.scope, audience: 'api://demo', used: false,
});
return res.json({
access_token: access,
refresh_token: newRefresh,
token_type: 'Bearer',
expires_in: parseInt(process.env.ACCESS_TOKEN_TTL, 10),
});
}
return res.status(400).json({ error: 'unsupported_grant_type' });
});
// --- JWKS endpoint (lets resource servers fetch the public key by kid) ---
app.get('/.well-known/jwks.json', (req, res) => {
// For demo we serve the single RSA public key. Real systems rotate and serve a list.
const pub = readPublicJwk();
res.json({ keys: [pub] });
});
function readPublicJwk() {
// Pre-convert your PEM to JWK at startup; here we just stub it.
return { kty: 'RSA', kid: process.env.KEY_ID, use: 'sig', alg: 'RS256',
n: '...modulus...', e: 'AQAB' };
}
app.listen(process.env.PORT_AUTH, () => {
console.log(Auth server on http://localhost:${process.env.PORT_AUTH});
});
markdown
Note the refresh-token reuse detection. When a refresh token is presented a second time, that means an attacker captured the first one and is replaying it. The correct response is to invalidate every refresh token in that family-every token derived from the original authorization grant-because you can no longer trust any of them. This is described in OAuth 2.0 Security BCP section 4.12. Skip this and you've built a system that silently leaks access for weeks.
Implementation: The Resource Server
src/resource-server.js:
JavaScriptCopy
javascript
import express from 'express';
import helmet from 'helmet';
import { verifyToken } from './jwt-utils.js';
import dotenv from 'dotenv';
dotenv.config();
const app = express();
app.use(helmet());
app.use(express.json());
// Auth middleware: validates Bearer token, enforces scopes
async function requireScopes(...required) {
return async (req, res, next) => {
const auth = req.headers.authorization || '';
if (!auth.startsWith('Bearer ')) {
return res.status(401).json({ error: 'invalid_token', error_description: 'missing' });
}
const token = auth.slice(7);
let payload;
try {
payload = await verifyToken(token, 'api://demo');
} catch (err) {
return res.status(401).json({
error: 'invalid_token',
error_description: err.code || 'verification_failed',
});
}
const scopes = (payload.scope || '').split(' ');
const ok = required.every(s => scopes.includes(s));
if (!ok) return res.status(403).json({ error: 'insufficient_scope', required });
req.user = { id: payload.sub, scope: scopes };
next();
};
}
app.get('/me', requireScopes('read'), (req, res) => {
res.json({ id: req.user.id, scope: req.user.scope });
});
app.delete('/account', requireScopes('delete'), (req, res) => {
res.json({ deleted: req.user.id });
});
app.listen(process.env.PORT_API, () => {
console.log(Resource API on http://localhost:${process.env.PORT_API});
});
The middleware does three things in order: presence check, signature+claims check, scope check. Each failure returns a different HTTP status (401 for "I don't know who you are," 403 for "I know who you are but you can't do that"). Don't conflate them-clients depend on this distinction to know whether to refresh the token or to give up.
The Client Side: Storing Tokens Without Getting XSS'd
This is where 90% of tutorials go wrong. They tell you to put your JWT in localStorage. That's the single most common cause of token theft in production web apps, because any XSS in your app-or in any of your 47 npm dependencies-can read localStorage and exfiltrate the token.
The correct pattern for SPAs:
- Access token: short-lived (5-15 min), held in memory (a JS variable). Lost on refresh, but that's fine-you use the refresh token immediately to get a new one.
- Refresh token: long-lived, stored in an HttpOnly, Secure, SameSite=Strict (or Lax) cookie that's only sent to the authorization server's token endpoint. Not readable by JS.
- CSRF protection: because cookies are involved, you need CSRF tokens on the token endpoint, or use the BFF (Backend-For-Frontend) pattern.
The BFF pattern is the cleanest answer. You put a thin server (or a serverless function) between your SPA and the AS. The SPA talks to the BFF over regular cookies, the BFF holds the tokens server-side and proxies API calls. This is what Next.js, Remix, and most modern meta-frameworks encourage. It's more code, but it's the only way to be both XSS-resistant and have proper revocation.
For native mobile apps, use the platform's secure storage-Keychain on iOS, Keystore on Android. Libraries like react-native-keychain, expo-secure-store, or flutter_secure_storage wrap this. Never store tokens in AsyncStorage or plain SharedPreferences.
| Storage | Web SPA | React Native | Server |
|---|---|---|---|
| Access token | In-memory | OS secure storage | Cache (Redis) keyed by user |
| Refresh token | HttpOnly cookie (BFF) | OS secure storage | DB with rotation metadata |
| ID token (OIDC) | Same as access | OS secure storage | Usually not stored |
| Client secret | N/A (public client) | N/A (public client) | Env var / secret manager |
Production Considerations
Token TTLs. Access tokens should be short. Five to fifteen minutes is the sweet spot. Longer = more damage if leaked. Shorter = more refresh churn and slightly worse UX. Refresh tokens: 7-30 days for consumer apps, 1-24 hours for high-security (banking, admin). Idle timeout matters too-if the user hasn't used the refresh token in 24h, expire it.
Key rotation. Rotate signing keys at least every 90 days, immediately on any suspected leak. Publish new keys to your JWKS endpoint, keep the old ones valid for a grace period (typically 2x the access-token TTL), then remove them. Clients fetch JWKS and should cache with a short TTL (5-15 min) and refetch on kid miss.
Revocation. JWTs are stateless-you can't revoke one without making the system stateful. Three patterns:
- Short TTL + accept the risk. Simplest. A leaked token dies in 15 minutes. Fine for most apps.
- Denylist of
jtis in Redis, checked on every request. Adds a Redis lookup to every API call. Use a TTL equal to the access-token TTL so the list stays small. - Token introspection (RFC 7662). Resource server calls the AS on every request to check if the token is still valid. Defeats the perf benefit of JWT entirely; consider opaque tokens instead.
Pick based on your threat model. Most apps don't need #2 or #3 for access tokens. They DO need them for refresh tokens, because a leaked refresh token is a long-term credential.
Rate limiting. The token endpoint is the highest-risk endpoint for brute force and credential stuffing. Limit per IP and per client_id. Add progressive backoff. Monitor for bursts of invalid_grant errors-those are attacks.
Logging. Log every token issuance with sub, client_id, scope, iat, and a request id. Never log the token itself, never log the code_verifier, never log refresh tokens. Use structured logging. Set up alerts on refresh-token-reuse detection-if it fires, you have an incident.
HTTPS everywhere, no exceptions. HSTS, no mixed content, certificate pinning on mobile. A single HTTP endpoint in your auth flow undoes everything else.
Common Mistakes and How to Detect Them
Storing JWT in localStorage. Detected by opening DevTools → Application → Local Storage and seeing access_token. Fix: move to BFF + HttpOnly cookie, or in-memory only.
Validating JWT signature but not aud or iss. A token issued by your staging AS will be accepted by your production API. Fix: always pass audience and issuer to jwtVerify. Even better, also check azp (authorized party) for client binding.
Accepting alg: none. The header literally says {"alg":"none"} and there's no signature. Old libraries accepted this. Fix: pin the algorithm, as shown above. Modern libs reject none by default but double-check.
Long-lived access tokens "for performance." I've seen 30-day access tokens in production. That's just a session token with extra steps. Fix: 15 min max, use refresh tokens.
Refresh token rotation without reuse detection. You rotate, but you don't track "used." An attacker captures a token, you both rotate from the same token, attacker now has a valid refresh chain forever. Fix: track used and burn the family on reuse.
Not validating redirect_uri exactly. Match on full string, not prefix. https://app.example.com/callback and https://app.example.com/callback/ are different. https://app.example.com/callback?foo=bar should be rejected unless the registered URI explicitly allows it.
Allowing wildcard CORS on the token endpoint. Fix: explicit origin allowlist, credentials: true, never *.
Trusting the sub claim from an untrusted issuer. If you federate with external IdPs, you must validate the issuer signature, not just decode the payload. Otherwise anyone can forge a token claiming to be user 1.
Troubleshooting: Real Production War Stories
Symptom: Every callback returns invalid_redirect_uri after deploying to staging.
Cause: The deploy script lowercased the URL. Registered: https://App.Example.com/callback. Requested: https://app.example.com/callback. Redirect URIs are case-sensitive per RFC 3986. Fix: normalize at registration time, document the case-sensitive gotcha in your onboarding.
Symptom: Tokens work for half the users, fail for the other half, error is signature verification failed.
Cause: Two auth-server pods, only one had the new key. JWKS endpoint returned the old public key, tokens signed by the new private key failed. Fix: deploy keys to all pods before promoting the new kid, or fetch JWKS at startup and on kid miss.
Symptom: Mobile app logs out randomly every 10-15 minutes.
Cause: Access token TTL was 15 min, refresh-token request was being blocked by an over-aggressive CORS preflight on the token endpoint. The preflight returned 403 because the client's Origin wasn't in the allowlist. Fix: allowlist the mobile app's origin (or use a custom scheme that the OS handles natively).
Symptom: Refresh-token reuse alerts fire constantly, but no actual breach.
Cause: The client had a bug where it sometimes issued two refresh requests in parallel (one from a tab, one from a service worker). The first succeeded, marked the token used, the second triggered reuse detection and burned the whole family. Fix: serialize refresh requests client-side (mutex or single-flight), make the AS tolerant of legitimate concurrent requests within a short window.
Symptom: aud claim mismatch errors after splitting the monolith into two services.
Cause: Both services were checking audience: 'api://demo', but the new service expected audience: 'api://billing'. Fix: mint audience-specific tokens, or use scope-based authorization if you want one token to work across services.
Testing, CI/CD, and the Auth Test Pyramid
Auth code is the worst place to find bugs in production. Test it heavily.
- Unit tests for JWT sign/verify (all algos, all claim combinations, expired tokens, wrong audience, wrong issuer).
- Integration tests that drive the full
/authorize→/token→ API call flow with a real HTTP client. - Negative tests for every error path: bad PKCE, used code, expired code, reused refresh, wrong redirect, missing scope.
- Property tests for token generation-random inputs shouldn't crash, tokens should round-trip.
- Load tests on the token endpoint. It's the one endpoint that gets hammered on every login and every refresh.
CI/CD considerations: keys should never live in the repo. Use your cloud's secret manager (AWS Secrets Manager, GCP Secret Manager, Azure Key Vault) and inject at deploy. Rotate keys via a CI job, not by hand. Run dependency scans-jose, express, anything crypto-adjacent-on every PR. Subscribe to security advisories.
A useful canary: deploy a synthetic client that logs in, calls the API, refreshes, and logs out every 5 minutes from every region. If auth breaks, you find out before your users do.
Alternatives and Cost Comparison
Unless you have a strong reason to build your own AS, don't. The cost of a bug in auth dwarfs the cost of any vendor.
| Option | Best for | Pricing (approx) | When to pick |
|---|---|---|---|
| Auth0 | Most teams, B2B and B2C | Free <7.5k MAU, then ~$35+/mo | You want a managed IdP with good DX |
| Clerk | B2C apps, React/Next.js | Free <10k MAU, then $25+/mo | You want drop-in components |
| WorkOS | B2B SaaS, SSO/SCIM | Free <1M users, $125+/mo for SSO | You need enterprise SSO fast |
| Keycloak | Self-hosted, full-featured | Free + hosting cost | You can't use cloud, or need full control |
| AWS Cognito | AWS-native apps | Free <50k MAU, then $0.0055/user-month | You're already on AWS and price-sensitive |
| Okta | Enterprise | $$$ enterprise contracts | You're selling to Fortune 500 |
| Custom (this article) | Niche requirements, learning | Engineering time + risk | You have unusual constraints |
For most early-stage teams I recommend Clerk or Auth0. The moment enterprise SSO becomes a sales blocker, layer WorkOS on top. Self-host Keycloak only if you have compliance reasons or you're at a scale where vendor pricing dominates your bill.
Real-World Use Cases
- B2B SaaS with multi-tenant SSO. Customer's IT team configures SAML/OIDC against your Auth0 tenant. Your app just sees a JWT. Onboarding a new enterprise customer is a 30-minute config task, not an integration project.
- Mobile app with social login. "Sign in with Apple" requirement for iOS apps. Auth Code+PKCE from the app, Sign in with Apple returns an ID token you validate and exchange for your app's session.
- Internal microservices. Client Credentials flow between services. Service A calls AS with its client_id+secret, gets an access token with
scope=orders:read, calls service B, service B validates the token and scope. Zero shared secrets. - Third-party API access. User connects their Slack account to your app. OAuth flow against Slack's AS, you get a refresh token, you can call Slack APIs on their behalf until they revoke.
- Machine-to-machine at scale. CLI tools authenticating with Device Code flow. User runs
mycli login, gets a URL+code, opens browser, approves, CLI polls the token endpoint until approved.
Wrapping Up
OAuth and JWT are deceptively simple on the surface and quietly hostile in the corners. The spec takes a weekend to read and a year to internalize. If you take one thing from this article: the security of your auth system lives in the trade-offs, not the code. Short TTLs, refresh rotation with reuse detection, RS256 with algorithm pinning, BFF pattern for browser apps, secure storage on mobile. Get those five things right and you've solved 95% of the real-world risk.
If you take two things: don't store JWTs in localStorage. Please. I'm begging you.
Originally published on Mango Developer.
