What is a JWT token and how does it work?
JWT was designed to solve a specific problem in stateless architectures: how do you verify who a user is on every API request without maintaining a session store that every server node must share? The answer is to give the client a signed token containing their identity, which they present with each request. The server verifies the signature using a secret key (HS256) or public key (RS256) and trusts the payload if the signature is valid.
The three parts of a JWT are visible as three Base64URL-encoded segments separated by periods. The header specifies the algorithm: {"alg":"HS256","typ":"JWT"}. The payload contains claims - standard ones like "sub" (subject, usually a user ID), "exp" (expiry timestamp in Unix seconds), "iat" (issued at), and "iss" (issuer), plus any custom claims your application needs like user roles or permissions. The signature is computed as HMAC-SHA256(base64(header) + "." + base64(payload), secret).
A critical misconception: JWT payloads are encoded, not encrypted. Anyone who intercepts a JWT can Base64-decode the payload and read everything in it. Never put sensitive data (passwords, card numbers, secrets) in a JWT payload unless you use JWE (JSON Web Encryption) instead of the standard JWS (JSON Web Signature). Always transmit JWTs over HTTPS.
Token expiry management is the main operational concern. Short-lived access tokens (15 minutes to 1 hour) combined with longer-lived refresh tokens give a good balance between security and user experience. If an access token is compromised, it expires quickly. The refresh token can be revoked server-side, which is the one database operation still required for proper logout.
A JWT decoder lets you inspect the header and payload of any JWT instantly - useful for debugging authentication issues without writing code.