JWT Authentication Flow
A JSON Web Token (JWT) is a compact, URL-safe token format used to represent claims between two parties. In authentication contexts, JWTs serve as self-contained access tokens that a server can validate without querying a database — making them ideal for stateless, horizontally-scaled APIs.
A JSON Web Token (JWT) is a compact, URL-safe token format used to represent claims between two parties. In authentication contexts, JWTs serve as self-contained access tokens that a server can validate without querying a database — making them ideal for stateless, horizontally-scaled APIs.
A JWT consists of three Base64URL-encoded parts separated by dots: a header (algorithm and token type), a payload (claims), and a signature. The header specifies the signing algorithm — typically HS256 (HMAC-SHA256, symmetric) or RS256 (RSA-SHA256, asymmetric). The payload contains standard claims like sub (subject/user ID), exp (expiry timestamp), iat (issued at), and iss (issuer), plus any application-specific claims like roles or permissions.
The flow begins with a login request. The client sends credentials (username + password, or an OAuth2 code) to the authentication server. After verifying the credentials, the server creates a JWT payload, signs it with the secret or private key, and returns the token to the client.
The client stores the JWT — typically in memory or an httpOnly cookie — and attaches it to every subsequent request as an Authorization: Bearer header. When the resource server receives the request, it extracts the token, decodes the header to identify the algorithm, fetches the public key or secret, and verifies the signature. It then checks exp to ensure the token hasn't expired. No database lookup is needed: all claims are self-contained.
The trade-off of statelessness is that JWTs cannot be revoked before expiry without maintaining a denylist. This is why access tokens are kept short-lived (5–60 minutes) and paired with a Refresh Token Rotation strategy. For session-based alternatives that are easier to invalidate, compare Session Based Authentication. Token revocation patterns are covered in Token Revocation Flow.