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
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 themRefresh 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.
