Skip to content

What’s inside a JWT

Working knowledgeUnder the hood

A JWT looks like a scrambled string, so it is easy to assume it hides something. It doesn’t. It is two pieces of readable JSON and a signature. Here is each byte’s job, and the one thing the signature actually guarantees.

01 Three parts and two dots

Here is a real HS256 token, made by the script further down. It is long, but it has only three parts, separated by the two dots.

Text
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJhbmEiLCJyb2xlIjoiY3VzdG9tZXIiLCJleHAiOjE3NjcyMjY1MDB9.sXkJgALOIqeXxp2JtPE1otoA9H4lsubeyrh_OH25QeI
The three parts of the token above
PartStartsLengthDecodes to
HeadereyJhbGci36 chars{"alg":"HS256","typ":"JWT"}
PayloadeyJzdWIi64 chars{"sub":"ana","role":"customer","exp":1767226500}
SignaturesXkJgALO43 chars32 raw bytes (an HMAC)

The format is defined in RFC 7519 (JWT) and RFC 7515 (JWS, the signed form). The payload’s fields are claims. A few names are registered: sub (who), exp (expires at), iat (issued at), iss (who issued it) and aud (who it is for). The rest, like role, are your own.

02 Base64url is packing, not hiding

Each JSON part is turned into text with base64url: the usual base64 alphabet with - and _ instead of + and /, and no = padding, so the token is safe in URLs and headers. It is an encoding, with no key. Anyone can reverse it.

Shell
echo 'eyJzdWIiOiJhbmEiLCJyb2xlIjoiY3VzdG9tZXIiLCJleHAiOjE3NjcyMjY1MDB9' | base64 -d
{"sub":"ana","role":"customer","exp":1767226500}

That is a real run on macOS. It works here with plain base64 because this part happens to be a multiple of 4 characters long and has no - or _. For other tokens, add = until the length is a multiple of 4 and swap -_ back to +/ first, or paste the token into a decoder.

Everything in the payload is readable by whoever holds the token: the user, their browser extensions, any log that records the header. Never put a password, an internal secret or personal data there that the holder should not see.

03 How the signature is made

The signature is computed over the encoded header and payload joined by a dot. With HS256 it is an HMAC with SHA-256: a hash that also mixes in a secret key, so only key holders can produce it.

Making an HS256 token
Step 1 of 7
The token being built (3 parts)
header—
payload—
signature—
Bytes in, text out
Empty
  • just made
  • fed into the HMAC
  • finished
  • not made yet

The server has checked Ana’s password. It knows the claims it wants to sign and holds a secret key. Nothing is encoded yet.

Change one character anywhere in the first 101, and the HMAC comes out unrelated to the old one. That is what makes the signature useful.

04 What the server checks

On every request the server repeats the HMAC with its own key and compares. It does not decrypt anything, and it needs no database: the key alone decides.

A token with an edited payload
Step 1 of 5
Token as received (payload edited)
headereyJhbGci…
payload…YWRtaW4i…
signaturesXkJgALO…
What the server works out
Empty
  • checking now
  • fed into the HMAC
  • just worked out
  • the outcome
  • not read yet

Ana decoded her payload, changed "customer" to "admin", re-encoded it and pasted it back between the dots. She kept the old signature, because she cannot make a new one. The server has its key and nothing else.

Compare the signatures with a constant-time function such as Python’s hmac.compare_digest or Node’s crypto.timingSafeEqual. A plain == can stop at the first differing byte, and the timing difference can leak how much of a guess was right.

05 Make and check one yourself

This script uses only the Python standard library. It signs a token, then tries three bad ones: an edited payload, an unsigned token claiming alg: none, and one whose exp has passed.

jwt_demo.py
import base64, hashlib, hmac, json, time
KEY = b"demo-key-use-32-random-bytes-in-real-life"
def b64url(raw: bytes) -> str:
return base64.urlsafe_b64encode(raw).rstrip(b"=").decode()
def unb64url(text: str) -> bytes:
return base64.urlsafe_b64decode(text + "=" * (-len(text) % 4))
def part(obj: dict) -> str:
return b64url(json.dumps(obj, separators=(",", ":")).encode())
def sign(claims: dict) -> str:
signing_input = part({"alg": "HS256", "typ": "JWT"}) + "." + part(claims)
mac = hmac.new(KEY, signing_input.encode(), hashlib.sha256).digest()
Text
$ python3 jwt_demo.py
good: ok, sub=ana
forged: rejected, bad signature
alg none: rejected, unexpected alg
expired: rejected, expired
payload, read without the key: {"sub":"ana","role":"customer","exp":1793584882}

That output is a real run with Python 3.14; your exp will differ because it is the current time plus 15 minutes. In an app, use a maintained library (PyJWT, jose for Node, jjwt for Java) and tell it which algorithms to accept. This script is for seeing the parts, not for production.

06 What signing protects, and what it doesn’t

A valid signature proves one thing: someone with the key produced these exact bytes. Everything else is up to you.

IntegrityProtectedNo one without the key can change a claim or invent a token that verifies.
SecrecyNot protectedThe payload is only encoded. If it must be hidden, use an encrypted JWT (JWE) or keep the data on the server.
Threats, and whether the signature stops them
ThreatSignature stops it?What does
Editing a claimYesThe HMAC no longer matches
Minting a token from scratchYes, without the keyKeep the key secret and long
Reading the payloadNoLeave secrets out, or use JWE
Replaying a stolen tokenNoShort `exp`, HTTPS, `HttpOnly` cookies
Using it after logoutNoShort `exp` plus a deny list or refresh tokens
A token meant for another serviceNoCheck `aud` and `iss`
A leaked keyNoRotate the key; every old token becomes invalid

07 HS256 or RS256: who can sign

With HS256 the same secret both signs and verifies. Every service that checks tokens can therefore also mint them. With RS256 or ES256, the issuer signs with a private key and every other service verifies with the matching public key, which cannot sign.

HS256 (HMAC)One shared secretSimple and fast. Fine when one service both issues and checks.
RS256 / ES256Private signs, public checksMany services can verify without being able to forge. Public keys are often published as a JWKS.

The format is the same either way: only alg in the header and the signature bytes change. Sessions vs tokens covers when a token is the right choice at all.

08 When it goes wrong

{"alg":"none"}Letting the header pick the algorithmSome early libraries accepted unsigned tokens that said alg: none. Pass the allowed algorithms to the verifier yourself.
RS256 → HS256Algorithm confusionIf a verifier expecting RS256 accepts HS256, an attacker can sign with your public key as the HMAC secret. Pinning the algorithm stops this too.
key = "secret"A guessable HMAC keyOne captured token is enough to test guesses offline, as fast as the attacker’s hardware allows. Use at least 32 random bytes.
jwt.decode(token)Decoding instead of verifyingMany libraries have a decode that skips the signature, for debugging. Code that reads claims from it trusts anything.
exp, aud uncheckedA valid signature, wrong tokenAn expired token, or one issued for another app with the same key, still verifies. Check exp, and aud and iss when you have several.

09 Check yourself

Question

You change "role":"customer" to "role":"admin" in a token’s payload and keep the original signature. What happens on an HS256 server that verifies correctly?

Question

Which of these does a JWT signature give you?

Question

Ten services must check tokens, but only the login service should create them. Which is the better fit?

10 Practise this

Was this tutorial useful?Your vote tells us what to improve next.
Spotted a mistake, or something unclear?