JSON Web Tokens explained
JWTs are everywhere in modern sign-in and APIs. This guide explains how they are built, how to read them and how to use them safely.
The three parts
A JWT looks like xxxxx.yyyyy.zzzzz. The first part is the header, a JSON object with the algorithm (alg) and type (typ). The second part is the payload with the claims. The third part is the signature, computed over the first two parts with a secret or private key. Each part is base64url encoded so it is safe in URLs and HTTP headers.
Registered claims
- iss (issuer): who created and signed the token.
- sub (subject): the user or service the token is about.
- aud (audience): which application should accept it.
- exp (expiration time): when the token stops being valid.
- nbf (not before): when the token starts being valid.
- iat (issued at): when the token was created.
- jti (JWT ID): a unique ID that can be used to block replays.
Access tokens and ID tokens
In OpenID Connect, an ID token tells the client application who signed in and contains profile claims such as name and email. An access token is sent to an API to prove what the caller may do, often with a scope claim. Access tokens should be short-lived, usually minutes to an hour, and refreshed with a refresh token.
Mistakes to avoid
- Decoding a token without verifying it, then trusting its claims.
- Accepting the algorithm named in the token instead of the one your server expects.
- Using a short, guessable HMAC secret. Use at least 32 random bytes.
- Storing sensitive data in the payload.
- Issuing tokens that never expire, or very long-lived access tokens.