Token-Based Auth and JWT

Use signed tokens such as JWTs for APIs and mobile clients, and understand their trade-offs versus sessions.

Intermediate · about 5 hours · difficulty 3/5

Learn first: Sessions and Cookies

With token-based authentication, the client holds a token and sends it in the Authorization: Bearer <token> header. A JSON Web Token (JWT) is a popular format: a header, a JSON payload of claims (sub, exp, iat, roles) and a signature, base64url-encoded and joined with dots.

How verification works

The server signs the token with a secret (HS256) or a private key (RS256, ES256). Any service with the secret or public key can verify it without a database lookup. That makes JWTs handy across multiple services and for mobile or third-party API clients.

The trade-offs

  • Revocation is hard: a stolen token is valid until it expires. Keep access tokens short-lived (5-15 minutes) and use a longer-lived refresh token that is stored server-side and can be revoked and rotated.
  • Payload is readable: signed does not mean encrypted. Never put secrets or sensitive personal data in claims.
  • Storage in browsers: tokens in localStorage are exposed to XSS. For browser apps, an HttpOnly cookie is often safer.

Verification checklist

Validate the signature, pin the allowed algorithms (reject none), check exp, nbf, iss and aud, and use a well-maintained library.

Also know

Opaque API keys for server-to-server access, and PASETO as a stricter token format.

You are ready to move on when you can implement access plus refresh tokens with rotation and explain how you would log out a user whose access token has not expired yet.

Key concepts

  • JWT structure and claims
  • HS256 vs RS256 signing
  • Access and refresh tokens
  • Refresh token rotation
  • Token storage in browsers
  • API keys
  • PASETO

Mini project

Build an auth service that issues 10-minute access tokens and rotating refresh tokens stored hashed in the database, with reuse detection that revokes the whole token family.

Check yourself

Why is a JWT that lives for 30 days risky, and what design reduces that risk?

Free resources