Skip to content
Blog

← All articles

The Ultimate Guide to JWT Architecture: Structure, Verification, and Common Flaws

How a JSON Web Token is built, how a server should verify one step by step, how keys and JWKS fit into a real system, and the flaws (alg none, algorithm confusion, weak secrets, kid and jku injection) that keep breaking JWT implementations.

By 22 min read

JSON Web Tokens are everywhere: behind “Sign in with Google”, in the Authorization header of almost every public API, and in a good share of security incident reports. The format itself is small enough to explain in a paragraph. Getting a system built on it right requires more care, because most failures don’t stem from broken cryptography. They come from code that trusts the token to specify how to check it.

This guide covers how a JWT is put together, where it fits in a real architecture, how a server should verify one, and the mistakes that keep turning up in audits and CVEs. Every code example was run before publishing, with jose 6.2 on Node.js 24 and PyJWT 2.15 on Python 3.12.

Prefer video? There’s a 13-minute version that covers the main points:

Nothing loads from YouTube until you press play. Watch on YouTube

What a JWT is (and isn’t)#

A JWT is a set of claims (statements such as “this is user 8231” or “this expires at 00:15 UTC”) packed into a URL-safe string and protected by a signature or by encryption. The standard is RFC 7519, and it builds on a family of specs called JOSE (JavaScript Object Signing and Encryption):

SpecWhat it defines
RFC 7515 JWSSigned content: the three-part tokens most people mean by “JWT”
RFC 7516 JWEEncrypted content: five-part tokens whose payload can’t be read without a key
RFC 7517 JWKKeys as JSON, and JWK Sets (JWKS) for publishing several of them
RFC 7518 JWAThe algorithm names: HS256, RS256, ES256 and the rest
RFC 8725 JWT BCPBest current practices: the security rules this guide keeps coming back to

Three things a JWT is not, because each one causes real bugs:

  • Not encrypted. A signed JWT is only encoded. Anyone holding the token can read every claim. The signature stops people from changing it, not from reading it.
  • Not a session by itself. A JWT is a signed statement that was true when it was issued. Unless you build something extra, nothing can “log it out” before it expires.
  • Not proof of who is sending it. A plain JWT is a bearer token: whoever has it can use it. If it leaks from a log file, the person who finds it is, as far as your API can tell, the user.

Anatomy of a token#

Here’s a real token. It was signed with HS256 and the secret correct-horse-battery-staple-2026:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJ1c2VyLTgyMzEiLCJuYW1lIjoiQWRhIExvdmVsYWNlIiwiYWRtaW4iOmZhbHNlLCJpYXQiOjE3OTQxODI0MDAsImV4cCI6MTc5NDE4MzMwMH0.xktefk-lPVL9kVkzDzYa2dm1KjQyVrm9vVZOwulfUi8

It’s three base64url strings joined by dots: the header, the payload, and the signature. Base64url is ordinary Base64 with - and _ instead of + and /, and with the = padding left off, so the token can go in a URL or a header without escaping. (That’s also why nearly every JWT starts with eyJ: it’s the Base64 of {" followed by the first letter of a key.)

Decoding the first two parts takes a few lines and no key at all:

decode.mjs
// decode.mjs: read a JWT's header and payload. This does NOT check the signature.
const token = process.argv[2];
const [header, payload] = token
  .split(".")
  .slice(0, 2)
  .map((part) => JSON.parse(Buffer.from(part, "base64url").toString("utf8")));

console.log({ header, payload });
output
{
  header: { alg: 'HS256', typ: 'JWT' },
  payload: {
    sub: 'user-8231',
    name: 'Ada Lovelace',
    admin: false,
    iat: 1794182400,
    exp: 1794183300
  }
}

The header

The header describes how the token is protected. alg names the algorithm and is required. typ says what kind of token this is. kid (key ID) tells the verifier which key was used, which is what makes key rotation possible. Other parameters exist, and some of them are dangerous to honor: jku and x5u (URLs to fetch keys from), jwk (a key embedded in the token itself) and crit (extensions the verifier must understand or else reject the token). The header is part of the signed data, but it’s also the part an attacker writes. Treat it as a hint, never as an instruction.

The payload

The payload is a JSON object of claims. Some names are registered by the RFC (next section), and the rest are yours: scope, tenant_id, roles. Keep it small, because the token travels with every request and cookies top out around 4 KB. Keep it free of secrets and personal data you wouldn’t print in a log.

The signature

The signature covers the exact bytes of the first two segments, dot included:

signature = base64url( SIGN( key, base64url(header) + "." + base64url(payload) ) )

Change a single character of the header or payload and the signature no longer matches. Because it’s computed over the encoded strings, not over the JSON, the verifier never has to re-serialize anything. That avoids a whole class of canonicalization bugs that plague XML signatures.

An encrypted token (JWE) has five parts instead of three: a header, an encrypted content key, an IV, the ciphertext, and an authentication tag. Its payload is often a signed JWT, a pattern called a nested JWT. If you see five dots-separated parts, it’s a JWE. Our JWE decoder will show you which part is which.

The claims that matter#

RFC 7519 registers seven claim names. They’re all optional in terms of format, but a verifier that ignores them is the root cause of many of the flaws later in this guide.

ClaimMeaningWhat the verifier must do
issIssuer: who made the tokenMatch it exactly against the issuer you trust
audAudience: who the token is for (a string or an array)Reject the token unless it names you
expExpiration timeReject it after this time (allowing a small clock skew)
nbfNot beforeReject it before this time
iatIssued atOptionally reject tokens that are too old or from the future
subSubject: who the token is aboutUse it as the user or client ID, scoped to the issuer
jtiJWT ID: unique per tokenUse it to detect replay or to revoke one token

The times are NumericDate values: whole seconds since 1970-01-01 UTC, not milliseconds. JavaScript’s Date.now() returns milliseconds, and passing it straight in produces a token that expires roughly 57,000 years from now. The sample token above has iat 1794182400 (2026-11-09 00:00 UTC) and exp 1794183300, fifteen minutes later.

sub is unique within one issuer. If your API trusts two identity providers, the pair (iss, sub) is the user’s ID, not sub alone.

Choosing a signing algorithm#

The algorithms fall into two families, and the difference matters more than which hash function they use.

algTypeKeySignature sizeUse it when
HS256 / HS384 / HS512HMAC (symmetric)One shared secret, at least as long as the hash (32 bytes for HS256)32–64 bytesThe same service issues and verifies
RS256 / RS384 / RS512RSA PKCS#1 v1.5RSA key pair, 2048 bits or more256 bytes (2048-bit key)You need the widest compatibility
PS256 / PS384 / PS512RSA-PSSRSA key pair256 bytesYou want RSA with the more modern padding
ES256 / ES384 / ES512ECDSAP-256, P-384 or P-521 key pair64 bytes (ES256)A good default for new systems
EdDSAEd25519Ed25519 key pair64 bytesFast and hard to misuse, where every verifier supports it

With HMAC, the key that verifies a token can also create one. Every service that checks HS256 tokens can therefore mint them, so compromising any verifier compromises the issuer. That’s fine for a single application signing its own session tokens, and wrong for a platform where ten microservices verify tokens from one login service.

With asymmetric algorithms, only the issuer holds the private key and everyone else gets the public key. A leaked public key is a non-event. That separation is what makes JWTs useful across services, and it’s why the rest of this guide assumes ES256. Size matters too: an ES256 signature is 86 characters of base64url, while RS256 with a 2048-bit key is 342.

One algorithm should never be accepted: none. It means “this token is not signed”. RFC 7519 allows it when the token is protected in another way, but in practice it is intended to be rejected.

Where JWTs fit in a system#

In most deployments, JWTs come from an OAuth 2.0 or OpenID Connect authorization server (Auth0, Okta, Entra ID, Cognito, Keycloak or your own). They are checked by APIs that never see a password:

The client gets a token from the authorization server, sends it to the API, and the API verifies it with the public keys from the JWKS endpoint.Clientbrowser, app, serviceAuthorization serverholds the private key/.well-known/jwks.jsonAPI (resource server)verifies, never signsJWKSpublic keys by kid,cached by the API1. log in2. access token3. Authorization: Bearer …publishes4. key for kid
The authorization server signs; APIs verify with public keys they fetch from the JWKS endpoint and cache.
  1. The client signs in with the authorization server.
  2. It gets back an access token (a JWT) and usually a refresh token.
  3. It sends the access token on each API call: Authorization: Bearer eyJ…
  4. The API reads the token’s kid, finds that public key in the issuer’s JWKS (fetched once and cached), verifies the token and its claims, and only then looks at what the user is allowed to do.

The appeal is that step 4 needs no database lookup and no call to the authorization server. The API can verify thousands of tokens a second on its own. The cost is the flip side of that independence: the API can’t know about anything that happened after the token was issued, such as a logout, a password change, or an account being disabled. The section on lifetimes and revocation deals with that.

Keys, kid and the JWKS

A JWK Set is a JSON document listing the issuer’s current public keys, each with a kid. OpenID Connect providers advertise it as jwks_uri in their discovery document (/.well-known/openid-configuration). The kid is what makes rotation painless:

  1. Generate the new key and publish it in the JWKS next to the old one.
  2. Wait until verifiers have had time to refresh their cache (longer than their cache lifetime).
  3. Start signing with the new key.
  4. Remove the old key once every token it signed has expired.

A good verifier refetches the JWKS when it sees a kid it doesn’t know, with a cooldown so a stream of made-up kid values can’t make it hammer the issuer. jose’s createRemoteJWKSet does this out of the box.

Access tokens, ID tokens and refresh tokens

These get mixed up, and the error is a vulnerability:

  • Access token: for APIs. Its aud is the API. When it’s a JWT, RFC 9068 gives it the header "typ": "at+jwt".
  • ID token: for the client, from OpenID Connect. It says who logged in. Its aud is the client’s ID. An API must never accept one as an access token.
  • Refresh token: for the authorization server only, to get new access tokens. Often not a JWT at all, and never sent to APIs.

Issuing tokens#

If you run the authorization server yourself, issuing is the easy half. This is the issuer from the diagram, using jose, which runs on Node.js, Deno, Bun, Cloudflare Workers, and in browsers:

issue.mjs
// issue.mjs: the authorization server signs a short-lived access token via its private key.
import { SignJWT, exportJWK, generateKeyPair } from "jose";

// In production, the key pair is created once and kept in a KMS or secrets store.
const { privateKey, publicKey } = await generateKeyPair("ES256", { extractable: true });
const kid = "2026-11-a";

// Publish the public half at https://auth.example.com/.well-known/jwks.json
const jwks = { keys: [{ ...(await exportJWK(publicKey)), kid, alg: "ES256", use: "sig" }] };
console.log(JSON.stringify(jwks));

const accessToken = await new SignJWT({ scope: "orders:read" })
  .setProtectedHeader({ alg: "ES256", kid, typ: "at+jwt" })
  .setIssuer("https://auth.example.com")
  .setAudience("https://api.example.com")
  .setSubject("user-8231")
  .setIssuedAt()
  .setExpirationTime("10m")
  .setJti(crypto.randomUUID())
  .sign(privateKey);

console.log(accessToken);

Every line here is doing a job:

  • kid in the header and the JWKS, so the key can be rotated later.
  • typ: at+jwt, so this token can’t be confused with an ID token or any other JWT the same key signs.
  • iss and aud, so an API can reject tokens from other issuers or meant for other APIs.
  • A short exp. Ten minutes is common for access tokens; anything over an hour should have a reason.
  • A random jti, so one token can be identified, logged, and, if needed, revoked.
  • Only the public key in the JWKS. exportJWK(publicKey) has no d member; publishing the private key by exporting the wrong half is a mistake that has happened in production.

Verifying a token, step by step#

Verification is where systems succeed or fail. The order matters: nothing from the token is trusted until the signature has been checked with a key you chose, using an algorithm you chose.

  1. 1Parse3 parts, base64url, JSON
  2. 2Headeralg allowlisted, typ, crit
  3. 3Keyfrom your store, by kid
  4. 4Signatureverify before reading
  5. 5Claimsexp, nbf, iss, aud
  6. 6Authorizesub, scope, your rules
Every step must pass. Claims are read only after the signature is verified.
  1. Parse. Exactly three segments for a JWS. Each must be valid base64url, and the header and payload must be JSON objects. Reject anything else, including tokens with five segments if you don’t expect JWE.
  2. Check the header. alg must be on your allowlist and must match the type of key you’ll use. Check typ if your tokens carry one. Reject the token if crit lists anything you don’t implement.
  3. Pick the key. Look up kid in the key set you already trust: your JWKS endpoint, configured ahead of time. Never fetch keys from a URL in the token (jku, x5u) and never use a key embedded in it (jwk).
  4. Verify the signature, with a constant-time comparison for HMAC.
  5. Validate the claims: exp and nbf with a small leeway (30 to 60 seconds for clock skew), iss exactly, aud includes you, and require the claims your application depends on.
  6. Authorize. Only now read sub, scope and your own claims to decide what the caller may do.

A well-maintained library does all of this in one call, provided you give it the options:

verify.mjs
// verify.mjs: the API checks every token before it trusts anything inside it.
import { createRemoteJWKSet, jwtVerify } from "jose";

// Fetched once, cached, and re-fetched when a token arrives with a kid it hasn't seen.
const JWKS = createRemoteJWKSet(new URL("https://auth.example.com/.well-known/jwks.json"));

export async function verifyAccessToken(token) {
  const { payload } = await jwtVerify(token, JWKS, {
    algorithms: ["ES256"], // the server decides, never the token
    issuer: "https://auth.example.com",
    audience: "https://api.example.com",
    typ: "at+jwt", // an ID token or refresh token can't be replayed as an access token
    requiredClaims: ["exp", "iat", "sub", "jti"],
    clockTolerance: "30s",
  });
  return payload; // only now is it safe to read sub, scope and the rest
}

Each option closes a hole. Without algorithms, jose would accept any algorithm the key type allows. Without issuer and audience, a token for a different API, or from a different tenant, would pass. Without typ, a valid ID token signed by the same key would pass as an access token. In testing, this function rejected tampered payloads, expired tokens, the wrong audience or issuer, a missing jti, tokens signed by an unknown key, alg: none and HS256, each with a specific error such as ERR_JWT_EXPIRED or ERR_JOSE_ALG_NOT_ALLOWED.

The same checks in Python with PyJWT:

verify.py
# verify.py: the same checks with PyJWT (pip install "pyjwt[crypto]")
from typing import Any

import jwt

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


def verify_access_token(token: str) -> dict[str, Any]:
    if jwt.get_unverified_header(token).get("typ") != "at+jwt":
        raise jwt.InvalidTokenError("not an access token")
    signing_key = jwks.get_signing_key_from_jwt(token)
    claims: dict[str, Any] = jwt.decode(
        token,
        signing_key.key,
        algorithms=["ES256"],
        audience="https://api.example.com",
        issuer="https://auth.example.com",
        leeway=30,
        options={"require": ["exp", "iat", "sub", "jti"]},
    )
    return claims

The function checks typ itself, from the unverified header, before anything else. That’s safe because it only ever rejects a token on that basis: nothing is granted until jwt.decode() has verified the signature. The code passes mypy --strict and produces the same results as the jose version when run against the same tokens.

Common flaws and how to avoid them#

These are the mistakes behind most real JWT vulnerabilities. Nearly all of them come down to one idea: the server let the token decide something the server should have decided.

Here’s a verifier with three of them at once. It looks reasonable, and it passes every test that uses honest tokens:

insecure-verify.mjs
// DON'T DO THIS: the token chooses the algorithm, and one "key" is used for every algorithm.
import crypto from "node:crypto";

export function insecureVerify(token, publicKeyPem) {
  const [h, p, s] = token.split(".");
  const header = JSON.parse(Buffer.from(h, "base64url"));
  const data = Buffer.from(`${h}.${p}`);
  let ok = false;
  if (header.alg === "none") ok = true; // flaw 1: unsigned tokens accepted
  if (header.alg === "HS256") ok = crypto.createHmac("sha256", publicKeyPem).update(data).digest("base64url") === s; // flaw 2
  if (header.alg === "RS256") ok = crypto.verify("sha256", data, publicKeyPem, Buffer.from(s, "base64url"));
  if (!ok) throw new Error("bad signature");
  return JSON.parse(Buffer.from(p, "base64url")); // flaw 3: exp, iss and aud never checked
}

1. Accepting alg: none

A token with {"alg": "none"} and an empty signature carries no proof at all. In 2015, several popular libraries accepted it whenever the header said so. The verifier above does the same in one line. The fix is an allowlist that doesn’t include none; jose refuses unsigned tokens in jwtVerify entirely.

2. Algorithm confusion (RS256 to HS256)

This is the classic, and it’s subtle. The server signs with RS256 and verifies with its RSA public key. The insecure verifier reads alg from the token and, for HS256, uses “the key” as an HMAC secret. But the public key is public, so anyone can compute that HMAC:

confusion.mjs
// The algorithm-confusion attack: an HS256 token "signed" with the server's PUBLIC key.
const b64url = (o) => Buffer.from(JSON.stringify(o)).toString("base64url");
const h = b64url({ alg: "HS256", typ: "JWT" });
const p = b64url({ sub: "admin", exp: Math.floor(Date.now() / 1000) + 3600 });
const s = crypto.createHmac("sha256", publicKeyPem).update(`${h}.${p}`).digest("base64url");
const forged = `${h}.${p}.${s}`; // insecureVerify() accepts this; jwtVerify() with algorithms: ["RS256"] doesn't

Run against the verifier above, this forged token is accepted with sub: admin. With jwtVerify(token, key, { algorithms: ["RS256"] }) it’s rejected before any signature is computed. The bug was reported in node-jsonwebtoken (CVE-2015-9235) and several other libraries at the time. The defense is twofold: an algorithm allowlist and keys bound to a single algorithm, so an RSA key can never be used as an HMAC secret. Modern libraries enforce the second; a hand-rolled verifier rarely does.

3. Weak HMAC secrets

An HS256 token is everything an attacker needs to test guesses at the secret offline, as fast as their GPUs allow. Password crackers such as hashcat have a built-in JWT mode. A secret like secret, changeme, or a company name can be revealed in seconds, and then the attacker can mint any token they like. RFC 7518 requires a key at least as long as the hash output: 256 random bits for HS256. Generate one, don’t think of one:

secret.sh
# 256 random bits for an HS256 secret (or 384/512 for HS384/HS512)
openssl rand -base64 32

The sample token in this article is a good example of what not to do: its secret is a memorable phrase, which is exactly the kind a wordlist contains.

4. Trusting kid, jku, x5u or jwk

These header parameters are attacker-controlled input, and each has its own failure mode:

  • kid used as a file path or SQL value. A server that loads keys/{kid}.pem can be pointed at ../../dev/null (an empty key, so an empty HMAC secret) or at any file whose contents the attacker can predict. A server that runs SELECT key FROM keys WHERE id = '{kid}' without parameters has a SQL injection. Treat kid as a lookup key into a map you control, nothing more.
  • jku and x5u. These tell the verifier where to download the key. Following them lets the attacker host their own key and sign anything, turning your API into a tool for making requests to internal URLs (SSRF). Ignore them, or match them against a fixed allowlist.
  • jwk. An embedded public key, which the verifier uses to verify the token it came in. That proves only that the token was signed by someone. Cisco’s node-jose had exactly this bug (CVE-2018-0114).

5. Not validating the claims

A valid signature only means your issuer made the token. Skipping the claims leaves the door open in other ways:

  • No exp check: a token stolen last year still works.
  • No aud check: a token issued for a low-value API (say, a public comments service) works against your payments API, if both trust the same issuer. With a large identity provider, that might be any app.
  • No iss check: on a multi-tenant provider, a token from another customer’s tenant may be signed by the same keys.
  • No typ check: RFC 8725 calls this cross-JWT confusion. An ID token, an email-verification link token, or a password-reset token signed by the same key can be replayed somewhere it was never meant to go.

6. Bugs in the cryptography itself

Rare, but they happen, and they’re the reason to keep runtimes and libraries patched. The best-known recent one is CVE-2022-21449, the “psychic signatures” bug: Java 15 to 18 accepted an ECDSA signature of all zeros as valid for any message as well as any key, so every ES256 token check in an unpatched JVM could be bypassed. It was fixed in Oracle’s April 2022 updates. Another class to be aware of is invalid-curve attacks on ECDH-ES in JWEs, where a library that doesn’t verify that a received public key is on the expected curve can leak the private key.

7. Secrets in the payload

Because the payload is just base64url, anything in it is visible to the user, to browser extensions, to proxies, and to every log that records an Authorization header. Email addresses, internal IDs, roles, and feature flags are commonly found there. If a claim must stay confidential, encrypt the token (JWE) or keep the data on the server and put only an opaque reference in the token.

Lifetimes, refresh and revocation#

A signed JWT remains valid until it expires, regardless of what happens in the meantime. That’s the price of verification without a database, and the standard way to keep it affordable is to make access tokens short-lived:

  • Short access tokens (5 to 15 minutes). A stolen one is only useful for a short time.
  • Refresh tokens to get new access tokens without signing in again. They’re checked against the authorization server’s database on every use, so they can be revoked, and logout, password changes and disabled accounts take effect at the next refresh.
  • Refresh token rotation: each refresh returns a new refresh token and invalidates the old one. If an old one is ever used again, someone copied it, and the whole chain should be revoked. The OAuth 2.0 Security BCP (RFC 9700) recommends this for public clients.

When minutes are too long, for example after a confirmed account takeover, you need state after all: a denylist of revoked jti values (kept only until each token’s exp), a per-user “tokens issued before this time are invalid” timestamp checked against iat, or token introspection (RFC 7662), where the API asks the authorization server about each token. All of these give up some of the statelessness, which is a fine trade for high-value operations.

Storing tokens in the browser#

There’s no perfect place for a token in a browser, only trade-offs:

WhereMain riskNotes
localStorage / sessionStorageXSSAny script on the page, including a compromised npm dependency, can read the token and send it away.
JavaScript memoryXSS (less)Gone on reload, so it needs a refresh flow; harder, but not impossible, to steal.
HttpOnly, Secure cookieCSRFScripts can’t read it, but the browser sends it automatically. Use SameSite=Lax or Strict, plus CSRF protection for state-changing requests.

For browser apps, the pattern the IETF’s guidance for browser-based OAuth apps now favors is a backend-for-frontend (BFF): a small server-side component that holds tokens, sets an HttpOnly session cookie for the browser, and attaches the access token when forwarding API calls. The tokens never reach JavaScript at all. Whatever you choose, an XSS hole is game over for the user’s session; storage choices only change how much the attacker can do after the tab is closed.

Checklist#

FAQ#

Is a JWT encrypted?

A normal (JWS) JWT is not. It’s signed and base64url-encoded, so anyone can read the payload. Only a JWE, with five parts instead of three, hides its contents.

Should I use HS256 or RS256?

HS256 if the same service creates and checks the tokens. An asymmetric algorithm (ES256, EdDSA, or RS256) if other services verify them, because with HS256 every verifier could additionally forge tokens.

Are JWTs better than session cookies?

Not in general. For a single web app talking to its own backend, a classic server-side session is simpler and easier to revoke. JWTs earn their keep when many independent services need to check identity without sharing a session store, or when tokens cross organizational boundaries, as in OAuth and OpenID Connect.

How long should a JWT be valid?

Access tokens: minutes, typically 5 to 15, at most an hour. Use refresh tokens for longer sessions, and make them revocable.

Can I log a user out of a JWT?

Not without state. Delete it on the client, revoke the refresh token so no new access tokens are issued, and, if it can’t wait for the access token to expire, add its jti to a denylist the APIs check.

Is it safe to paste a token into an online decoder?

Only one that runs entirely in your browser, and preferably not with a production token at all, since a live token is a working credential. Our JWT decoder does everything locally: nothing you paste is uploaded.

Get the code

  • jwt-dpop-sample on GitHub: an ASP.NET Core API and Angular client that use JWS, JWE, jti and DPoP together, with integration tests for stolen, replayed and forged tokens.

Try it in your browser