Orofold Labs

Launching soon

Notes Get in touch

Engineering 3 min read Updated

API authentication: cookies, JWT or API keys?

In short

Most web apps need stateful HttpOnly session cookies for browsers and hashed, scoped API keys for server-to-server integrations. Choose stateless JWTs only when multiple independent services must verify identity without calling a central store.

Choosing how callers authenticate to your API often gets decided by habit rather than threat model: teams put JSON Web Tokens (JWTs) into localStorage for a single-server web app, or issue permanent admin-level API keys without rotation. Matching the authentication mechanism to who is calling—a browser session, a third-party user grant, or an automated server integration—prevents most token-theft and revocation headaches.

Session cookies, JWT / OAuth 2.0 and API keys compared

MechanismBest suited forRevocationKey browser / client risk
Stateful session cookiesFirst-party web apps and B2B dashboards in a browserInstant (delete session row on server)Requires CSRF protection and HttpOnly / SameSite flags
OAuth 2.0 + short-lived JWTDelegated third-party access (RFC 6749) or multi-service architecturesDelayed until token expiry unless paired with server revocationAlgorithm confusion, leaked signing keys, or storing bearer tokens in JS-readable storage
Scoped API keysServer-to-server integrations, webhooks and CLI toolsInstant per key ID on server lookupLong lifetime if no expiry, rotation or scope limit is enforced

Why browsers still favour HttpOnly session cookies

When your frontend and backend live under the same site, storing an opaque session identifier in a HttpOnly; Secure; SameSite=Lax (or Strict) cookie keeps the credential invisible to JavaScript—so an XSS flaw cannot immediately read and exfiltrate it to another domain. See Sessions and cookies for cookie attributes and CSRF protection for state-changing requests.

By contrast, keeping a long-lived bearer JWT inside localStorage exposes it to any injected script, third-party widget or compromised dependency running on the page.

When OAuth 2.0 and JWT actually earn their complexity

As defined in OAuth 2.0 and RFC 6749, OAuth solves delegated authorisation: letting a third-party app act on a user’s behalf with limited scopes without handing over the user’s password. Signed JWTs work well as short-lived access tokens (for example, 5 to 15 minutes) when separate backend services must verify claims locally without calling a central session database on every request.

When using JWTs, follow the OWASP REST Security Cheat Sheet: pin an explicit allowed signing algorithm on the server (never accept alg=none or trust the token header blindly), validate iss, aud and exp on every request, and pair short access tokens with rotatable, revocable refresh tokens on the server.

Designing API keys for server-to-server callers

Customers automating orders, feeds or exports need non-interactive credentials. Build API keys with strict operational hygiene from the start:

  • Hash before storing: generate a high-entropy random token with a clear prefix (for identification), display the raw secret once at creation, and store only its cryptographic hash in the database (see Secrets management).
  • Narrow scopes and tenant binding: bind every key to one tenant and explicit capabilities (for example, orders:read rather than full workspace admin).
  • Overlap-friendly rotation: allow two active keys per integration briefly so customers can deploy a new key before revoking the old one.
  • Rate limits and audit logs: enforce per-key throttling (Rate limiting) and record last-used timestamp and key ID—never log the raw secret header.

Quick selection checklist

  1. User signing in through a browser to your own web product → HttpOnly stateful session cookies.
  2. External app asking a user for permission to access limited scopes → OAuth 2.0 (Authorization Code + PKCE).
  3. Customer script or ERP syncing data server-to-server → Hashed, scoped, rotatable API keys.
  4. Independent microservices verifying caller claims offline → Short-lived JWTs with pinned algorithms and server-side refresh revocation.

Do not mix sensitive PII into unencrypted JWT payloads—a standard signed JWS token is Base64URL-encoded, not encrypted, so anyone holding the token can read its claims.

Sources and limits

Designing API authentication for a new platform or integration layer? Describe your setup through our enquiry form.

Common questions

Should a browser single-page app store JWT access tokens in localStorage?
Avoid storing long-lived bearer tokens in localStorage because any XSS script can read them. For first-party web apps sharing a site, HttpOnly, Secure, SameSite session cookies paired with CSRF protection keep tokens inaccessible to JavaScript.
What is the main operational drawback of stateless JWTs?
Because a self-contained JWT stays valid until its exp timestamp without hitting the database, immediate revocation on password reset or account suspension requires short lifetimes plus a server-side revocation list or refresh-token check.
How should API keys be stored on the server?
Store a cryptographic hash of the API key rather than plaintext, show the raw secret only once at creation, attach narrow scopes and expiration dates, and log key IDs (never raw keys) for audit and rotation.

Sources

  1. OAuth 2.0, OAuth Community (oauth.net). Accessed 24 November 2026
  2. RFC 6749: The OAuth 2.0 Authorization Framework, IETF Datatracker. Accessed 24 November 2026
  3. REST Security Cheat Sheet, OWASP Foundation. Accessed 24 November 2026

Further reading

Have an idea that should exist? Or a working product that needs more customers, a new website or a complete rework? Bring us anything. Apply with your idea

All notes