Script Valley
REST API Development: Beginner to Production
Authentication and AuthorizationLesson 4.1

JWT authentication โ€” how JSON Web Tokens work

JWT structure, header, payload, signature, base64url encoding, signing algorithms, HS256 vs RS256, token expiry, stateless auth

How JSON Web Tokens Work

A JWT is a self-contained token that proves identity without requiring the server to store session state. It has three dot-separated segments: header, payload, and signature.

JWT Structure

// Decoded JWT
Header:  { "alg": "HS256", "typ": "JWT" }
Payload: { "sub": "user_42", "role": "admin", "exp": 1718000000, "iat": 1717996400 }
Signature: HMACSHA256(base64url(header) + "." + base64url(payload), secret)

The server signs the header and payload using a secret (HS256) or private key (RS256). On each request, the server re-computes the signature and compares it โ€” if it matches, the payload is trusted. The payload is base64url-encoded, not encrypted โ€” never put sensitive data in it.

Generating and Verifying JWTs in Node.js

npm install jsonwebtoken
const jwt = require('jsonwebtoken');

// Generate โ€” called at login
const token = jwt.sign(
  { sub: user.id, role: user.role },
  process.env.JWT_SECRET,
  { expiresIn: '15m' }
);

// Verify โ€” called in auth middleware
try {
  const decoded = jwt.verify(token, process.env.JWT_SECRET);
  console.log(decoded.sub); // user ID
} catch (err) {
  // TokenExpiredError, JsonWebTokenError
  res.status(401).json({ error: 'Invalid token' });
}

Use short expiry (15m) for access tokens. Longer-lived refresh tokens (covered in the next lesson) extend sessions without requiring re-login.

Up next

Implementing login and JWT auth middleware in Express

Sign in to track progress

JWT authentication โ€” how JSON Web Tokens work โ€” Authentication and Authorization โ€” REST API Development: Beginner to Production โ€” Script Valley โ€” Script Valley