Case Study · Auth · 2022 — 2023

Authentication — short-lived tokens, safe rotation

Secure auth flow with short-lived access tokens, refresh rotation, and middleware-guarded routes.

Spec Sheet

Role

Full-stack engineer

Timeline

2022 — 2023

Status

In production

Surface

Auth service + middleware

Stack

Next.js · Node.js

Data

Redis · JWT

01

Problem


The product needed authentication that was secure by default — resistant to token theft and replay — without forcing users to log in constantly. Long-lived tokens are convenient but dangerous; a single leaked token grants indefinite access. The challenge was balancing security with a smooth session experience.

02

Context & constraints


A multi-tenant SaaS with both browser and API clients. Tokens had to be verifiable statelessly at the edge for performance, yet revocable when a session was compromised — two goals that pull in opposite directions.

Short-lived accessaccess tokens expire in minutes, not days
Refresh rotationeach refresh issues a new token, old one revoked
Revocabilitya stolen session can be killed immediately
03

Architecture


Request path

Login

credentials

Auth service

verify

JWT

access + refresh

Middleware

validate

Protected route

granted

Failure recovery & consistency

Access expired

401

Refresh

rotate token

Reuse detected

revoke all

Re-login

forced

04

Implementation


Frontend

  • ·Silent refresh before access token expiry
  • ·Tokens in httpOnly cookies, not localStorage
  • ·Auto-redirect to login on hard 401

Backend

  • ·Stateless JWT verification (signature + exp)
  • ·Refresh token rotation with reuse detection
  • ·Redis denylist for revoked sessions

APIs

  • ·POST /auth/login
  • ·POST /auth/refresh (rotating)
  • ·POST /auth/logout (revokes session)
  • ·Middleware guard on protected routes
05

Key decisions


01

Short-lived access + rotating refresh

Access tokens live for minutes so a leak has a tiny window. Refresh tokens rotate on every use, so a stolen refresh token is detectable when the original is replayed.

02

Refresh-token reuse detection

If a rotated (already-used) refresh token is presented, the whole session family is revoked. This turns a token theft into a self-defeating attack rather than silent persistence.

03

httpOnly cookies over localStorage

Storing tokens in httpOnly cookies keeps them out of reach of XSS-injected JavaScript, trading a little client convenience for a meaningfully smaller attack surface.

06

Tradeoffs


Chose

·Stateless JWT verification at the edge

·Rotation + denylist for revocability

·httpOnly cookies for token storage

Gave up

·Fully stateless logout (needs the Redis denylist)

·Simpler client code (silent refresh adds logic)

·Long sessions without re-auth on sensitive actions

07

Outcome


minutes

max exposure window for a leaked access token

100%

compromised sessions revocable in real time

0

tokens reachable by injected client-side scripts