JSON Web Tokens Explained
Take a JWT apart, learn what its signature does and does not protect, and follow the checks every server should make.
Key takeaways
- A signed JWT has three Base64url parts separated by dots: header, payload and signature.
- The payload is readable by anyone holding the token, so never put secrets in it.
- A server must verify the signature with an algorithm it chose itself, then check issuer, audience and expiry.
- Because tokens are self-contained, revoking one before it expires takes extra design, so keep lifetimes short.
- For a single web application, an ordinary server-side session is often simpler and easier to cancel.
A JSON Web Token, or JWT, is a compact string that carries a set of statements, called claims, in a form the receiver can check for tampering. A server that issued one, or that trusts the issuer's key, can read who the token is about and when it expires without looking anything up in a session database.
The most common kind is signed, not encrypted. Anyone who gets the token can read its contents. The signature only proves that the contents haven't been changed since a holder of the signing key created them. The format is defined in RFC 7519.
The three parts
A signed token looks like three runs of letters and numbers joined by periods:
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiI1OCIsImV4cCI6MTc5MDAwMDAwMH0.c2lnbmF0dXJl The first two parts are JSON objects encoded with Base64url, the URL-safe variant described in Base64 explained. The third is the signature, shown here as a placeholder.
Dots separate the parts. Encoding is not encryption.
Decoding the first part above gives {"alg":"HS256","typ":"JWT"}. The second gives {"sub":"58","exp":1790000000}. No key was needed to read either one. That surprises people who see an unreadable string and assume it's locked. The difference is covered in hashing vs. encryption vs. encoding.
The standard claims
The payload can hold any JSON values, but RFC 7519 registers short names for common ones.
| Claim | Meaning |
|---|---|
iss | Issuer: who created the token |
sub | Subject: whom or what it's about |
aud | Audience: which service should accept it |
exp | Expiration time |
nbf | Not before: earliest valid time |
iat | Issued at |
jti | A unique identifier for the token |
Times are numbers of seconds since the start of 1970 in UTC, the format discussed in Unix timestamps and time zones. Applications add their own claims, such as roles or a tenant identifier. Keep the set small, since the token travels with every request.
How signing works
The issuer encodes the header and payload, joins them with a dot and computes a signature over that text. Two families of algorithm are common.
Shared secret algorithms such as HS256 use HMAC with SHA-256. The same secret creates and verifies tokens, so every service that can check a token can also forge one. This suits a single application that issues and consumes its own tokens. The secret must be long and random, because a weak one can be guessed offline by anyone holding a sample token.
Public key algorithms such as RS256 (RSA) or ES256 (elliptic curve) sign with a private key and verify with a public key. Only the issuer can create tokens, while any number of services can check them. Issuers often publish their public keys as a JSON Web Key Set, and the token header's kid field says which one to use. The idea is the same as in digital signatures.
A typical login with tokens
In an HTTP request it usually looks like this:
GET /v1/profile HTTP/1.1
Host: api.example.com
Authorization: Bearer eyJhbGciOi... It's a bearer credential, so whoever has it can use it until it expires. JWTs often serve as access tokens or as the ID token in OpenID Connect, both introduced in API keys, tokens and OAuth.
What the server must check
Decoding a token is not validating it. Use a maintained library and configure it to do all of the following:
- Fix the allowed algorithms. Decide in your configuration, not from the token's header. Historic flaws came from libraries accepting
none(no signature) or treating a public key as an HMAC secret. - Verify the signature with the correct key. If you use
kid, look it up only among keys you already trust. - Check
expandnbf, allowing only a small margin for clock differences. - Check
issmatches the issuer you expect. - Check
audincludes your service, so a token meant for another API isn't accepted by yours. - Check the token's purpose. An ID token shouldn't be accepted where an access token belongs.
Then apply your own authorization rules. A valid token saying "user 58" doesn't mean user 58 may read invoice 900. RFC 8725 collects best current practices for JWTs and is worth reading before you build on them.
The revocation problem
A server-side session can be deleted, and the user is signed out on the next request. A self-contained token keeps working until it expires, even if the account was disabled or the user pressed "log out".
The usual answers are:
- Short access token lifetimes, measured in minutes, with a refresh token that can be revoked.
- A deny list of
jtivalues checked for sensitive operations. - A per-user "tokens issued before this time are invalid" value.
- Rotating the signing key, which cancels everything signed with the old one.
Each deny list or lookup brings back some of the state that tokens were meant to avoid. That trade is fine if you choose it knowingly.
Where to keep tokens in a browser
Storing a token in localStorage is convenient, but any script running on the page can read it, so a cross-site scripting flaw hands it to an attacker. A cookie marked HttpOnly, Secure and with a SameSite setting can't be read by scripts. Cookies are sent automatically, though, so you also need to guard against cross-site request forgery. See how cookies work and injection and scripting flaws.
Whatever you pick, keep tokens out of URLs, which end up in logs and history.
Encrypted tokens
The JOSE family of standards also includes JSON Web Encryption, which produces a five-part token whose contents are unreadable without a key. It's useful when a token must carry data the holder shouldn't see. It adds key management, and it's usually simpler to keep sensitive data on the server and put only an identifier in the token.
Managing and rotating keys
A signing key is the most sensitive item in the whole system: whoever holds it can mint a token for any user. Keep it in a secrets manager or a hardware-backed key service, not in a source file, and limit which machines can read it.
Plan to replace it before you need to. With public key signing, rotation can happen without an outage:
- Create a new key pair and publish the new public key beside the old one, each with its own
kid. - Wait long enough for verifiers to refresh their cached copy of the key set.
- Start signing with the new private key.
- After the longest token lifetime has passed, remove the old public key.
Verifiers should cache the key set and refetch it when they see an unfamiliar kid, with a limit on how often, so a stream of made-up identifiers can't make your server hammer the issuer. They should fetch it only from an address set in configuration. A token that names its own key location mustn't be believed.
If a key leaks, skip the gentle schedule. Replace it at once, accept that everyone has to sign in again, and review what could have been accessed in the meantime.
Debugging a rejected token
When a service refuses a token you think is fine, the cause is usually mundane. Work down this list:
- The token expired, or the two machines' clocks disagree.
- The audience names a different service, such as a staging API.
- The issuer string differs by something as small as a trailing slash.
- The verifier holds an old public key, or the wrong environment's key.
- Part of the string was lost when copying, or the word
Bearerwas included twice. - The algorithm configured on the verifier doesn't match the one used to sign.
Log which check failed on the server side, without logging the token itself. Tell the client no more than it needs.
Should you use JWTs at all?
Tokens make sense when several services need to verify identity independently, or when you're consuming tokens from an identity provider. For one web application with one database, a random session ID in a cookie is shorter, trivially revocable and has fewer ways to go wrong.
If you need to inspect a token while debugging, decode it locally, for instance by splitting at the dots and running each of the first two parts through a Base64 converter that handles the URL-safe alphabet. Use test tokens only. A real, unexpired token pasted into a stranger's website or a public bug report is a handed-over credential.
Common questions
Can a user edit their own token to become an admin?
They can edit the text, but the signature will no longer match. A server that verifies correctly rejects it. A server that only decodes the payload is wide open.
Is a longer signing secret really necessary?
Yes for HMAC algorithms. Use random bytes at least as long as the hash output, 256 bits for HS256, generated by a cryptographic random source, not a memorable phrase.