Understanding JWT Tokens: A Developer's Complete Guide

JSON Web Tokens (JWTs) are everywhere — API authentication, single sign-on, microservices communication. If you build web applications, you'll work with them. This guide covers the structure, how they work, and the security practices that actually matter.

What Is a JWT?

A JWT is a compact claims format defined by RFC 7519. It can use a signed or MAC-protected JWS representation or an encrypted JWE representation. This guide explains the common signed JWS form; decoding alone does not establish authenticity.

A JWT looks like this:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c

Three parts separated by dots: Header, Payload, and Signature.

The Three Parts

1. Header

The header specifies the signing algorithm and token type. It's Base64url-encoded JSON:

{
  "alg": "HS256",
  "typ": "JWT"
}

Common algorithms: HS256 (HMAC + SHA-256, symmetric), RS256 (RSA + SHA-256, asymmetric), ES256 (ECDSA + SHA-256, asymmetric).

2. Payload

The payload contains claims — key-value pairs with information about the user and token metadata:

{
  "sub": "user-12345",
  "name": "Jane Developer",
  "email": "[email protected]",
  "role": "admin",
  "iat": 1711234567,
  "exp": 1711238167
}

Registered claims (standard fields):

  • sub — Subject (user ID)
  • iat — Issued at (Unix timestamp)
  • exp — Expiration time (Unix timestamp)
  • iss — Issuer (who created the token)
  • aud — Audience (who the token is for)
  • nbf — Not before (token not valid before this time)
  • jti — JWT ID (unique identifier for the token)

You can add any custom claims you need (role, permissions, org_id, etc.).

Important: The payload is Base64url-encoded, not encrypted. Anyone with the token can read its contents. Never put sensitive data (passwords, credit card numbers, secrets) in a JWT payload.

3. Signature

For HS256, compute an HMAC over the encoded header and payload with a shared secret key:

HMACSHA256(
  base64UrlEncode(header) + "." + base64UrlEncode(payload),
  secret
)

The signature lets the server verify that the token hasn't been modified. If someone changes a claim in the payload, the signature won't match and the token is rejected.

How JWT Authentication Works

  1. User logs in — Client sends credentials (username + password) to the server.
  2. Server creates JWT — After verifying credentials, the server creates a JWT with user claims, signs it, and returns it.
  3. Client stores JWT — The token is stored (usually in memory or an httpOnly cookie).
  4. Client sends JWT with requests — Each API request includes the token in the Authorization: Bearer <token> header.
  5. Server validates JWT — The server uses a trusted key and configured algorithm allowlist, then enforces required issuer, audience, expiry, and not-before claims before authorization.

HS256 vs RS256: Symmetric vs Asymmetric

HS256 (HMAC) uses a single shared secret for both signing and verification. Simple, fast, but every service that verifies tokens needs the secret — a security risk in distributed systems.

RS256 (RSA) uses a private key to sign and a public key to verify. Only the auth server needs the private key; all other services use the public key. Ideal for microservices architectures.

HS256: auth-server signs with SECRET → api-server verifies with SECRET
RS256: auth-server signs with PRIVATE_KEY ? api-server verifies with PUBLIC_KEY

Security Best Practices

Token Storage

  • Cookie storage: HttpOnly prevents JavaScript cookie reads, but does not prevent XSS or authenticated requests from injected scripts. Also use Secure, appropriate SameSite settings, CSRF protection, and XSS defenses.
  • In-memory storage: Lost on refresh, but still accessible to injected JavaScript while the page is running; not an XSS defense.
  • Avoid: localStorage or sessionStorage — accessible to any JavaScript on the page, including XSS payloads

Always Validate These

  • Signature — Never trust an unverified token
  • exp claim — Reject expired tokens
  • iss claim — Confirm the token came from your auth server
  • aud claim — Confirm the token is meant for your service
  • alg header — Reject "alg": "none" (a classic attack vector)

Token Expiration

Choose short access-token lifetimes and refresh-token controls for the application risk; 5–15 minutes is an example, not a universal requirement. This limits the damage window if a token is stolen.

Access token:  exp = 15 minutes
Refresh token: exp = 7 days (stored in httpOnly cookie, rotated on use)

Token Revocation

JWT verification can be stateless, but revocation commonly requires server-side controls. Options include token-identifier blocklists, session or account-version checks, and introspection. Design logout and compromise recovery explicitly rather than assuming one revocation method fits every system.

Common Mistakes

  • Putting secrets in the payload — The payload is readable by anyone.
  • Algorithm validation — Require a server-configured algorithm allowlist and trusted keys. Reject unsecured tokens where authenticated claims are required; rejecting none alone is insufficient.
  • Not checking expiration — Tokens without exp never expire. Always set and enforce expiration.
  • Long-lived tokens with no rotation — A stolen token that's valid for months is a serious risk.
  • Storing tokens in localStorage — Vulnerable to XSS. Use httpOnly cookies instead.

When NOT to Use JWTs

  • Session management for a monolith — Server-side sessions with a session ID cookie are simpler and easier to revoke.
  • Storing large amounts of data — JWTs are sent with every request. Keep claims limited to what is needed and account for actual proxy, header, and cookie limits; 1 KB is not a JWT standard limit.
  • When you need instant revocation — If immediate logout is critical, server-side sessions are more straightforward.

Try It Yourself

Paste a non-sensitive signed JWT example into the JWT Decoder tool to instantly see its header, payload, and expiration — decoded in the browser without signature verification. Page assets and services may still use the network.

Want to inspect a token?

Open JWT Decoder →