Script Valley
HTTP & The Web: How It Actually Works
REST APIs and Web Communication PatternsLesson 5.2

JWT authentication: how tokens work end to end

JWT structure, header payload signature, base64url encoding, HMAC vs RSA signing, token expiry, refresh tokens, bearer authentication, JWT validation

How JWTs Work

JWT structure header payload signature diagram

A JWT (JSON Web Token) is a base64url-encoded, signed JSON structure that clients use to prove their identity on every request without the server storing session state.

JWT structure

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9   # Header (base64url)
.eyJ1c2VySWQiOiI0MiIsImV4cCI6MTcxMH0   # Payload (base64url)
.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV    # Signature (HMAC-SHA256)

Decoded, the three parts are:

Header: specifies the algorithm, e.g. alg HS256 and typ JWT.

Payload: contains claims โ€” userId, exp (expiry Unix timestamp), role. Not encrypted โ€” anyone with the token can decode and read it. Never store passwords or PII here.

Signature: HMAC-SHA256 computed over the header and payload using a server-side secret. The server re-computes this on every request; if the payload has been tampered with, the signature will not match and the token is rejected.

Validation flow

1. Decode header to get the signing algorithm
2. Recompute signature using the secret/public key
3. Compare with token signature โ€” mismatch means reject
4. Check exp claim โ€” token expired means reject
5. Check iss and aud claims if your API uses them

Refresh tokens

Access tokens should be short-lived (15โ€“60 minutes). Refresh tokens are long-lived, stored in an HttpOnly cookie, and used to issue new access tokens without requiring re-login. If an access token leaks, the damage window is limited to its lifetime. Refresh token rotation (issue a new refresh token on every use) limits replay attacks.

Up next

WebSockets vs Server-Sent Events vs polling: when to use each

Sign in to track progress

JWT authentication: how tokens work end to end โ€” REST APIs and Web Communication Patterns โ€” HTTP & The Web: How It Actually Works โ€” Script Valley โ€” Script Valley