AskDB
·6 min read

JWT Explained: How JSON Web Tokens Work

JSON Web Token (JWT) is the most widely used token format for API authentication. Understanding how JWT works is essential for building secure applications.

What is a JWT?

A JWT is a compact, URL-safe token that contains claims (user data). It is digitally signed so the server can verify it was not tampered with.

Structure

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.
eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkFsaWNlIiwiaWF0IjoxNTE2MjM5MDIyfQ.
SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c

// Three parts separated by dots:
// 1. Header (algorithm & type)
// 2. Payload (claims)
// 3. Signature (verification)

Header

{
  "alg": "HS256",  // HMAC SHA-256
  "typ": "JWT"
}

Payload (Claims)

{
  "sub": "1234567890",    // Subject (user ID)
  "name": "Alice",        // Custom claim
  "email": "alice@test.com",
  "iat": 1516239022,      // Issued at
  "exp": 1516242622,      // Expiration time
  "iss": "myapp.com"      // Issuer
}

How Authentication Works

// 1. User logs in
POST /auth/login
{ "email": "alice@test.com", "password": "secret" }

// 2. Server returns JWT
{ "token": "eyJhbGciOi..." }

// 3. Client sends JWT with requests
GET /api/profile
Authorization: Bearer eyJhbGciOi...

// 4. Server verifies JWT and returns data

Access Tokens vs Refresh Tokens

// Access token: short-lived (15 min - 1 hour)
// Used for API requests

// Refresh token: long-lived (days - weeks)
// Used to get new access tokens
POST /auth/refresh
{ "refreshToken": "abc123" }
-> { "token": "new-access-token" }

Where to Store Tokens

  • localStorage — simple, persists across tabs, vulnerable to XSS
  • sessionStorage — cleared on tab close, vulnerable to XSS
  • httpOnly cookie — not accessible via JS, most secure against XSS
  • Memory (variable) — lost on page refresh, most secure

Security Best Practices

  • Use short expiration for access tokens (15 min)
  • Use refresh tokens for getting new access tokens
  • Store tokens in httpOnly cookies when possible
  • Always use HTTPS
  • Validate token signature on every request
  • Do not store sensitive data in JWT payload (it is base64, not encrypted)
  • Implement token revocation for logout

JWT vs Sessions

  • JWT — stateless, scalable, no server storage needed
  • Sessions — stateful, server stores session data, easier to revoke
  • JWT is better for APIs and microservices
  • Sessions are better for traditional web apps

Decode JWT

The payload is base64-encoded. Use the Base64 decoder to inspect JWT payloads during development.