What this article answers
What a JWT is, what each segment holds, and in what order to verify it. How attacks work and why defences fail belong to JWT security best practices; this piece covers reading and verifying only.
A JWT (RFC 7519) packs claims into JSON and signs it, guaranteeing integrity, not confidentiality. A server can confirm "I issued this token and nobody edited it" without a database lookup — the core value that lets it replace sessions.
The three segments
Three Base64Url strings joined by dots:
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c
Drop it into the JWT parser and all three segments appear; to understand the mechanics, decode the first two yourself with the Base64 converter.
Header
{ "alg": "HS256", "typ": "JWT" }
| Field | Meaning | Common values |
|---|---|---|
alg |
Signing algorithm | HS256 / RS256 / ES256 / EdDSA / none |
typ |
Token type | JWT |
kid |
Key ID | Locates the public key in a JWKS; required for rotation |
jku |
JWKS URL | The server should not trust it — see the security guide |
alg is declared by the token, not a trusted input. The verification side must choose the algorithm from its own configuration; get this wrong and everything downstream is moot.
Payload
Claims fall into three groups: registered claims defined by RFC 7519, public claims that need collision-free names, and private claims agreed between parties. The registered set is what matters:
| Claim | Meaning | Notes |
|---|---|---|
iss |
Issuer | Prefer a full URL such as https://auth.example.com |
sub |
Subject | Usually the user id — globally unique and never reused |
aud |
Audience | String or array; the verifier must find itself in it |
exp |
Expiration time | Unix timestamp in seconds |
nbf |
Not before | Tokens earlier than this must be rejected |
iat |
Issued at | Lets you compute token age |
jti |
JWT ID | The key to replay protection and deny-lists |
⚠️ Timestamps are in seconds, not milliseconds. Passing
Date.now()straight through yields an expiry decades away — one of the most common production blunders.
Namespace public claims (for example https://oltool.net/claims/role) and keep private claims such as role or tenant_id from colliding with standard names.
Signature
The signature covers the first two segments. For HS256:
HMACSHA256(
base64UrlEncode(header) + "." + base64UrlEncode(payload),
secret
)
RS256 is RSASSA-PKCS1-v1_5(SHA-256, signingInput); ES256 is ECDSA(P-256, SHA-256). The key point: the signature encrypts nothing. It keyed-digests the exact byte string of the first two segments and appends the Base64Url result. Verification recomputes it from the same input and compares.
Base64Url is not secrecy
Base64Url only makes binary safe for URLs. Copy the payload into the Base64 converter and the JSON is back in seconds.
Safe to include: user id, roles, tenant, expiry, scopes, session identifier.
Never include: passwords, keys, national ID numbers, card numbers, full phone numbers, internal topology.
When confidentiality is genuinely required, use JWE (RFC 7516, a five-segment structure and a different standard from JWS). In most cases the right answer is not JWE but keeping sensitive data out of the token entirely — a token proves identity, it is not a database row.
Choosing a signing algorithm
| Algorithm | Type | Key size | Signature size | Use when |
|---|---|---|---|---|
HS256 |
Symmetric HMAC | ≥ 256 bit random | 43 B | One service issues and verifies |
HS384 / HS512 |
Symmetric HMAC | ≥ 384 / 512 bit | 64 / 86 B | Compliance demands a stronger digest |
RS256 |
RSA PKCS#1 | ≥ 2048 bit (3072 preferred) | 342 B | Distributed systems where compatibility wins |
PS256 |
RSA-PSS | ≥ 2048 bit | 342 B | Probabilistic signatures, padding-attack resistance |
ES256 |
ECDSA P-256 | 256 bit | 86 B | Mobile or bandwidth-sensitive clients |
EdDSA |
Ed25519 | 256 bit | 86 B | Greenfield systems, no nonce pitfalls |
Decision order:
- Issuer and verifier are the same single service →
HS256. - Multiple verifiers or third parties →
RS256(compatibility first) orES256(size first). - Brand-new system, both ends under your control →
EdDSA, avoiding ECDSA nonce-reuse risk. - National-algorithm or regulatory requirements → follow the mandated suite.
Mint a keypair with the RSA key generator; to see how a keyed digest differs from a bare hash, compare the HMAC generator with the hash tool.
The seven-step verification order
Verification is not "the library returned true". Production code must run this sequence:
- Structure: exactly three segments, each valid Base64Url.
- Algorithm allow-list: read permitted
algvalues from server config — never let the token choose which key is used. - Resolve the key: by
kidwhen present; otherwise the single configured key. - Verify the signature: before parsing any claim.
- Time: check
exp(with leeway),nbf, and thatiatis not in the future. - Origin: check
issandaudagainst this service. - Business rules: is
jtideny-listed, is the user still valid, do the scopes cover this request?
Step 2 is the one that gets skipped, and it is the root cause of most JWT breaches — not broken cryptography, but a server that trusted the algorithm declared inside the token.
// ✅ Correct: the algorithm is pinned on the verifying side
jwt.verify(token, publicKey, { algorithms: ['RS256'], issuer, audience });
// ❌ Dangerous: the library picks the algorithm from the token
jwt.verify(token, key); // an attacker switches to HS256 and signs with your public key
Return 401 for a failed verification (WWW-Authenticate: Bearer error="invalid_token") and 403 for insufficient scope. The two mean different things; never downgrade a 403 to 404.
When not to use a JWT
| Dimension | Session + cookie | JWT |
|---|---|---|
| Server state | Session store required (memory / Redis) | Stateless; the token is self-contained |
| Horizontal scaling | Needs shared storage or sticky sessions | Just add machines |
| Cross-domain / cross-service | Cookie domain rules get painful | Lives in the Authorization header, naturally cross-origin |
| Revocation | Delete it server-side and it dies | Not revocable by default; needs extra design |
| Payload size | Just a session id | Carries every claim, so headers get bigger |
If you need instant revocation and tight control, sessions are less work. If you run multiple services, multiple clients, and need to scale out, JWTs fit better. Three more cases to skip JWTs:
- Admin back-offices needing second-level revocation — sessions are simpler and safer.
- Treating the JWT as a full session bucket — the payload travels on every request; overstuffing slows APIs and can exceed gateway header limits.
- Using it instead of encryption for sensitive data — that is JWE's or TLS's job.
Reproducible results
What each segment really is — decoding by hand beats any tool for intuition:
import base64, json
def b64url_d(s): return json.loads(base64.urlsafe_b64decode(s + '=' * (-len(s) % 4)))
header, payload, signature = token.split('.')
print(b64url_d(header)) # → {"alg": "HS256", "typ": "JWT"}
print(b64url_d(payload)) # → {"sub": "1", "exp": 1735689600, ...}
# signature is an HMAC over the first two segments — verifying needs the key; decoding does not
Decodable ≠ verified: anyone can craft a header and payload, so authorisation must rest on server-side signature verification. JWT security best practices includes a hand-built alg:none demo; to inspect segments only, use the JWT parser.