Understanding and verifying a JWT

Anyone can read a JWT and nobody can forge one, provided it is verified correctly. Here is how.

Three parts separated by dots

A signed JWT (JSON Web Token, RFC 7519) follows the structure header.payload.signature. Here is a sample token, broken at each dot for readability:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9
.eyJpc3MiOiJodHRwczovL2F1dGguZXhhbXBsZS5jb20iLCJzdWIiOiI0MiIsImF1ZCI6ImFwaS5leGFtcGxlLmNvbSIsImlhdCI6MTc2NzIyNTYwMCwiZXhwIjoxNzY3MjI2NTAwfQ
.adfOybV2mTy1XRpXl9KHylGP_ynTOIvcDmxYPiD2_8A

The first two parts are encoded JSON:

{"alg":"HS256","typ":"JWT"}

{"iss":"https://auth.example.com","sub":"42","aud":"api.example.com",
 "iat":1767225600,"exp":1767226500}

The header announces the signing algorithm. The payload carries the claims, the statements the token makes. The third part is the signature, computed over the string header.payload exactly as written. This token is signed with HS256 and the sample secret your-256-bit-secret: paste it into the kit's JWT decoder to see each part and verify its signature.

Base64url: an encoding anyone can read

Each part is encoded in Base64url, the Base64 variant that replaces + and / with - and _ and drops the = padding, so the token travels unchanged in a URL or an HTTP header. It is an encoding, with no key: whoever holds the token can read its content. The signature guarantees that nobody has changed it; it hides nothing. Keep the payload to information the token holder may see, and choose JWE, the encrypted form, when the content must stay confidential.

The registered claims

RFC 7519 defines seven short names, all optional, that libraries know how to check:

ClaimNamePurpose
issIssuerWho issued the token.
subSubjectWho the token is about, often a user ID.
audAudienceWho the token is meant for: a string or an array.
expExpiration TimeFrom this moment on, the token must be rejected.
nbfNot BeforeBefore this moment, the token must be rejected.
iatIssued AtWhen the token was issued.
jtiJWT IDA unique identifier for the token, useful against replay.

Timestamps are numbers of seconds since 1 January 1970 UTC. In JavaScript, Date.now() returns milliseconds: divide by 1,000 before comparing.

HS256 versus RS256, ES256 and EdDSA

HS256, HS384 and HS512 compute an HMAC with a shared secret: the same secret signs and verifies. They suit a single service that issues and verifies its own tokens. Every service that verifies can also sign, which calls for a random secret of at least 256 bits for HS256, kept like any secret key.

Asymmetric algorithms split the roles: the issuer signs with its private key, and anyone verifies with the public key. RS256 and PS256 use RSA, ES256 the P-256 curve, and EdDSA most often the Ed25519 curve, with keys and signatures much shorter than RSA's. They are the natural choice as soon as several services, or third parties, verify tokens from the same issuer.

JWKS and kid: finding the right public key

An identity provider publishes its public keys in a JWKS (JSON Web Key Set, RFC 7517), a JSON document whose keys array holds one entry per key. With OpenID Connect, its address is in the jwks_uri field of the /.well-known/openid-configuration document. The token header names the signing key with its kid. This makes rotation smooth: the provider publishes the new key before using it, and keeps the old one until the tokens it signed have expired.

Configure the JWKS address on the server. The jku and x5u headers, which point to a key location from inside the token itself, are checked against a list of trusted addresses before any use.

The checks a server must make

  1. A list of algorithms fixed on the server. The header's alg is compared with this list; it never replaces it. alg: none means an unsigned token and stays off the list.
  2. The signature, with the key expected for that algorithm. This is what defeats algorithm confusion: if a server built for RS256 lets the token pick HS256, an attacker computes an HMAC with the RSA public key, which is public by definition, and a naive library accepts it.
  3. exp and nbf, with a small leeway for clock skew: a few seconds, at most a few minutes according to the RFC.
  4. iss, which must be exactly the expected issuer.
  5. aud, which must contain your API's identifier: a token issued for another service of the same provider carries a valid signature too.

In Node.js with the jose library, these checks fit in the options of jwtVerify, which throws on the first failure:

import { createRemoteJWKSet, jwtVerify } from 'jose';

const jwks = createRemoteJWKSet(new URL('https://auth.example.com/.well-known/jwks.json'));

const { payload } = await jwtVerify(token, jwks, {
  algorithms: ['RS256'],
  issuer: 'https://auth.example.com',
  audience: 'api.example.com',
  clockTolerance: 30, // seconds
});

In Python, PyJWT (installed with pip install "pyjwt[crypto]" for RSA and elliptic curves) does the same:

import jwt

jwks = jwt.PyJWKClient("https://auth.example.com/.well-known/jwks.json")
key = jwks.get_signing_key_from_jwt(token).key

payload = jwt.decode(
    token,
    key,
    algorithms=["RS256"],
    issuer="https://auth.example.com",
    audience="api.example.com",
    leeway=30,
)

Short lifetimes and revocation

A server verifies a JWT without querying a database: that is its strength, and it also means an issued token stays valid until its exp. Revocation therefore relies on a short lifetime, a few minutes for an access token, renewed through a refresh token that the server can revoke. To cut off one specific token, a list of revoked jti values, kept until they expire, does the job. Changing the signing key invalidates every token in circulation at once.

Where to keep a token

  • In the browser, an HttpOnly, Secure, SameSite cookie keeps the token out of reach of the page's scripts. localStorage, on the other hand, is readable by any script: a single XSS flaw is enough to copy it.
  • In headers, as Authorization: Bearer …, rather than in a URL, which ends up in the history, in server logs and in the Referer header.
  • Out of logs: mask the Authorization header there, and keep tokens out of Git repositories, tickets and screenshots.

Sharing a token

When debugging as a team, you sometimes need to hand a token to a colleague. With “Send with onlyU”, the decoder passes the token to onlyU from one tab to another in your browser, never in an address and never through the kit's server. onlyU encrypts it in your browser and creates a link your recipient opens only once, valid for 24 hours, after which the link disappears. It is free and requires no sign-up. The token remains usable until it expires: prefer a short-lived token issued for the occasion.