HomeBlogHow to Build Secure Authentication Using...

Engineering Guide · 9 min read · October 19, 2026

How to Build Secure Authentication Using JWT and Refresh Tokens

Most JWT tutorials stop at signing a long-lived token and storing it in localStorage—leaving applications exposed to XSS theft and impossible logout revocation. Here is the production architecture for short-lived access tokens, HttpOnly cookie transport, refresh token rotation, and automatic reuse detection.

Author
Smit Desai
Published
October 19, 2026
Read time
9 min read
Topic
Full-Stack Web
Services
Custom Web · Mobile Apps · All Services

JSON Web Tokens remain the most consistently misconfigured piece of application security I encounter during production code reviews. Nearly every vulnerable setup traces back to the same five-minute quickstart: issue a JWT valid for 30 days, return it inside the login JSON body, persist it in localStorage, and verify the signature in route middleware.

In live software, that shortcut fails in two severe ways: you cannot invalidate a stolen token before day 30, and any XSS payload or compromised third-party tag manager can read localStorage silently.

When your architecture genuinely calls for JWTs—across decoupled mobile clients, cross-origin APIs, or distributed microservices—you must combine short-lived stateless access tokens with stateful, single-use refresh tokens.

Step One: Verify That You Actually Need JWTs

Before writing rotation tables and lock logic, confirm whether classic server-side sessions (backed by Redis or PostgreSQL behind an HttpOnly cookie) serve your product more cleanly.

When your web frontend and API share one registrable domain (app.acme.test and api.acme.test), opaque session cookies offer instant revocation, zero client-side refresh races, and straightforward permission invalidation. Reach for Access JWT + Refresh Token specifically when:

  • Native iOS or Android clients authenticate alongside a browser app.
  • Separate backend microservices verify identity locally using public keys (JWKS) without calling a central session database on every request.
  • Third-party API consumers require scoped short-lived bearer credentials.

Access vs. Refresh Responsibilities and Storage

Splitting credentials into two distinct tokens balances stateless verification speed against real session control:

  1. Access JWT: Expires in 5–15 minutes, signed asymmetrically (EdDSA or RS256), kept strictly in memory (or a short-lived HttpOnly cookie), never persisted in localStorage.
  2. Refresh Token (Opaque Secret): A 256-bit cryptographically random string—never a JWT—hashed via SHA-256 before database storage, valid for 7–30 days, and accepted once at /auth/refresh.

Client Transport Security Matrix

Runtime Target Access Token Placement Refresh Token Placement Cross-Site Request Protection
Browser SPA JS memory or HttpOnly cookie HttpOnly, Secure, SameSite=Lax cookie (Path=/auth/refresh) SameSite policy + Origin verification
iOS / Android App In-memory state store Keychain (iOS) / EncryptedSharedPreferences (Android) Not needed (Authorization: Bearer header)
Anti-Pattern localStorage / sessionStorage localStorage Exposed to any inline or third-party script

Scoping the browser cookie with Path=/auth/refresh ensures the refresh credential never rides along on ordinary /api/* calls, minimizing exposure in proxy logs.

Schema Design for Rotation and Reuse Detection

To revoke sessions cleanly and catch token replay attacks, store SHA-256 digests in auth_refresh_tokens grouped under a chain_id representing one device login:

CREATE TABLE auth_refresh_tokens (
  token_id UUID PRIMARY KEY,
  account_id UUID NOT NULL REFERENCES accounts(id) ON DELETE CASCADE,
  chain_id UUID NOT NULL,
  sha256_digest CHAR(64) NOT NULL UNIQUE,
  superseded_by UUID NULL REFERENCES auth_refresh_tokens(token_id),
  invalidated_at TIMESTAMP WITH TIME ZONE NULL,
  valid_until TIMESTAMP WITH TIME ZONE NOT NULL,
  issued_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP
);

CREATE INDEX idx_auth_refresh_chain ON auth_refresh_tokens (chain_id);

Because only sha256_digest hits disk, even a leaked database snapshot cannot be replayed directly against your refresh endpoint.

Atomic Rotation and Automatic Reuse Detection

Each call to /auth/refresh locks the matching token row, marks it superseded, and mints a fresh (accessToken, refreshToken) pair inside the same chain_id.

If an attacker steals an older refresh token and submits it after the legitimate user has already rotated forward—or vice versa—the server spots that superseded_by or invalidated_at is already populated and revokes the entire chain_id immediately:

import crypto from "node:crypto";

export async function rotateSessionTokens(db: Database, rawRefresh: string) {
  const digest = crypto.createHash("sha256").update(rawRefresh).digest("hex");

  return db.transaction(async (tx) => {
    // Row lock serializes parallel tab refresh requests
    const current = await tx.queryOne(
      `SELECT * FROM auth_refresh_tokens WHERE sha256_digest = $1 FOR UPDATE`,
      [digest]
    );

    if (!current || current.valid_until < new Date()) {
      throw new AuthError("TOKEN_EXPIRED_OR_UNKNOWN");
    }

    // Reuse detected: invalidate entire login chain
    if (current.superseded_by !== null || current.invalidated_at !== null) {
      await tx.execute(
        `UPDATE auth_refresh_tokens SET invalidated_at = NOW() WHERE chain_id = $1 AND invalidated_at IS NULL`,
        [current.chain_id]
      );
      throw new AuthError("REFRESH_TOKEN_REUSE_DETECTED");
    }

    const nextSecret = crypto.randomBytes(32).toString("base64url");
    const nextDigest = crypto.createHash("sha256").update(nextSecret).digest("hex");
    const nextTokenId = crypto.randomUUID();

    await tx.execute(
      `INSERT INTO auth_refresh_tokens (token_id, account_id, chain_id, sha256_digest, valid_until)
       VALUES ($1, $2, $3, $4, NOW() + INTERVAL '14 days')`,
      [nextTokenId, current.account_id, current.chain_id, nextDigest]
    );

    await tx.execute(
      `UPDATE auth_refresh_tokens SET superseded_by = $1 WHERE token_id = $2`,
      [nextTokenId, current.token_id]
    );

    const accessJwt = issueShortAccessJwt({
      sub: current.account_id,
      jti: crypto.randomUUID(),
      expiresInSeconds: 600,
    });

    return { accessJwt, refreshToken: nextSecret };
  });
}

Preventing Multi-Tab False Positives in Browsers

When a user leaves three tabs open and returns after 15 minutes, all three tabs hit 401 and call /auth/refresh simultaneously with the identical cookie. Without coordination, tab #2 trips reuse detection and forces a logout.

Prevent false alarms cleanly:

  1. Single-flight refresh lock: Deduplicate concurrent refresh promises inside your frontend HTTP client and coordinate across tabs via navigator.locks or BroadcastChannel (patterns frequently covered on Vercel's engineering blog).
  2. Row-level serialization (FOR UPDATE): Ensures the server processes overlapping requests sequentially rather than racing two inserts.

Verification Hardening and Key Rotation Pitfalls

Even solid refresh flows break if JWT signature verification skips basic guardrails:

  • Explicit algorithm allow-lists: Never trust the incoming alg header blindly (which enables alg: none or asymmetric-to-HMAC downgrade attacks). Pass algorithms: ['EdDSA'] or ['RS256'] explicitly to your verifier.
  • Strict iss, aud, and minimal clock leeway: Cap clock skew tolerance under 30 seconds and enforce environment-specific audience strings so staging tokens cannot hit production APIs.
  • Lean claims only: Include sub, tid (for multi-tenant isolation), exp, iat, and jti. Avoid stuffing huge RBAC arrays or sensitive PII into Base64-encoded payloads visible in browser devtools or logs.
  • Zero-downtime signing key rotation via kid: Serve active public keys from /.well-known/jwks.json keyed by kid so key rotations never invalidate live 10-minute access tokens.

For broader guidance on isolating identity boundaries from domain logic, review Martin Fowler's architecture patterns, or read how we extract coupled session logic when modularizing older PHP codebases.

Shipping Hardened Auth Layers With SmitDev

Authentication leaves zero margin for guesswork—one missing cookie attribute, unvalidated alg header, or race-prone refresh handler compromises user trust overnight. Across 170+ shipped systems since 2017, I regularly build and audit HttpOnly cookie BFF proxies, rotating refresh pipelines, OAuth2/SSO flows, and tenant-scoped RBAC.

Engage SmitDev directly via dedicated engineering retainers or full-stack development services at $55/day (8–9 hours of daily engineering) or $1,999/month for continuous delivery. Share your current auth flow or stack constraints on our contact page for a concrete hardening plan.

Written by Smit Desai · Principal Full-Stack & FDSE

8+ years shipping production systems · 171 case studies · 300+ WordPress servers managed for Finland partners.

Next Steps and Recommended Resources

Next Steps · Recommended Resources

Pillar 1 · Custom Web & SaaS

Custom Web Application Development

Production Laravel, Next.js, API, and multi-tenant SaaS systems engineered end to end at $55/day (8–9 hrs) or $1,999/mo.

Comparison · Buyer Guide

SmitDev vs Software Agencies

See side-by-side economics, senior code ownership, and onboarding speed vs traditional dev shops and marketplaces.

01 — Frequently asked questions

full-stack web

Why shouldn't I store JWT access or refresh tokens in localStorage?

Any JavaScript running on your origin—including third-party analytics scripts or an XSS vulnerability—can read localStorage. Storing tokens in HttpOnly, Secure, SameSite cookies keeps credentials completely inaccessible to client-side JavaScript.

How long should JWT access tokens and refresh tokens live?

Keep access tokens short-lived—typically 5 to 15 minutes—so a leaked token expires quickly without needing global revocation checks on every API call. Refresh tokens can last 7 to 30 days when rotated on every use and tracked server-side.

How does refresh token reuse detection stop stolen tokens?

Each refresh token is single-use and belongs to a token family. If an attacker replays an already-rotated refresh token, the server detects the reuse, immediately revokes the entire token family, and forces re-authentication for both the attacker and the legitimate session.

Does SmitDev build or audit authentication and security layers for client apps?

Yes. Across 170+ client projects, SmitDev regularly implements and audits auth, RBAC, SSO, and session security at $55/day (8–9 hours) or $1,999/month dedicated delivery.

03 — Have an engineering need?

hire the right expertise

Let's talk tech.

Deciding between an embedded forward deployed engineer or a senior full stack developer? Share your technical context and timeline.

Solitaire Corporate Park, Makarba, Ahmedabad, Gujarat 380015, India · IST (UTC+5:30) · --:-- IST · Mon–Fri 09:00–18:00 IST · US & EU overlap daily

No newsletter, no CRM. Just a reply.