Complete Guide to JWT Token Parsing & Verification

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:

  1. Issuer and verifier are the same single service → HS256.
  2. Multiple verifiers or third parties → RS256 (compatibility first) or ES256 (size first).
  3. Brand-new system, both ends under your control → EdDSA, avoiding ECDSA nonce-reuse risk.
  4. 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:

  1. Structure: exactly three segments, each valid Base64Url.
  2. Algorithm allow-list: read permitted alg values from server config — never let the token choose which key is used.
  3. Resolve the key: by kid when present; otherwise the single configured key.
  4. Verify the signature: before parsing any claim.
  5. Time: check exp (with leeway), nbf, and that iat is not in the future.
  6. Origin: check iss and aud against this service.
  7. Business rules: is jti deny-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.

Frequently Asked Questions

The JWT payload looks like gibberish — why do you call it plaintext?

JWTs use Base64Url *encoding*, not encryption. Any tool reverses it in three seconds. Open the [JWT parser](/jwt-parser.html), or paste the middle segment into the [Base64 converter](/base64-converter.html), and the payload becomes readable immediately. Never put passwords, ID numbers, or secrets in a JWT — only non-sensitive identifiers and timestamps.

Should I use HS256 or RS256?

When a single service both issues and verifies the token, HS256 is simplest: one shared secret, fast, hard to get wrong. Whenever the issuer and the verifier are *different* services — microservices, third-party APIs, mobile backends — use RS256 or ES256: sign with a private key, verify with a public key. Verifiers never need the ability to mint tokens, and a leaked public key does not compromise security. ES256 gives shorter, faster signatures; RS256 has the broadest compatibility.

Once a JWT is issued, can it ever be revoked?

A server-side session can be deleted outright; a self-contained JWT cannot, because the server holds no state. Three workarounds: (1) shorten the lifetime (5–15 minutes for access tokens) until the revocation window is acceptable; (2) keep a deny-list of revoked jti values that have not yet expired — this reintroduces state; (3) store a token_version on the user row, embed it in the payload at issue time, and bump it on password change or logout-everywhere. Options 1 and 3 cover most products.

Should a JWT live in localStorage or in a cookie?

Neither is absolutely safe; they fail in different ways. localStorage can be read by any XSS payload, but you control exactly when the token is sent. An HttpOnly + Secure + SameSite cookie cannot be read by script, but it is attached automatically to same-site requests, so you need separate CSRF protection. The current mainstream recommendation: keep the access token in memory (a variable or closure), put the refresh token in an HttpOnly cookie scoped to a dedicated path, and add SameSite=None plus a CSRF token for cross-site flows.

Why does JWT verification keep saying the token is not yet valid inside a container?

nbf (Not Before) is set from the issuer clock, so any drift between client and server triggers a false rejection — common on Kubernetes nodes, in CI, and across time zones. Two fixes: issue tokens from a single NTP-synced time source, and configure a 30–60 second leeway in your verification library (clockTolerance in jsonwebtoken, leeway in PyJWT). Remember that leeway applies to exp too, so keep it under a minute or you are simply extending token lifetime.

← Back to Blog