JSON Web Tokens (JWT) explained: structure, validation and security pitfalls

What a JWT is, how its header, payload and signature work, which claims to validate, HS256 vs RS256, where to store tokens, and the security mistakes to avoid.

JSON Web Tokens — JWTs, often pronounced “jots” — are everywhere in modern web and mobile apps. When you log in to an app and it talks to its API, there is a good chance a JWT is being sent with every request to prove who you are.

JWTs are useful, standardised and supported by libraries in every major language. They are also easy to misuse in ways that create serious security holes. This guide explains how they work, what a server must check, and the mistakes to avoid. You can take apart any token with our JWT decoder, which runs entirely in your browser.

What a JWT is

A JWT is a compact string that carries a set of claims — statements such as “this is user 123” and “this token expires at 14:00 UTC” — together with a signature that lets the receiver check the claims haven’t been changed. The format is defined in RFC 7519, alongside related standards for signing (JWS) and encryption (JWE).

A typical signed JWT looks like three chunks of characters separated by dots:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjMiLCJleHAiOjE3NjQzMzEyMDB9.4Xb...

Those three parts are the header, the payload and the signature.

The three parts

The header is a small JSON object describing the token, most importantly the signing algorithm:

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

Payload

The payload is a JSON object containing the claims:

{ "sub": "123", "name": "Sample User", "iat": 1764200000, "exp": 1764203600 }

Signature

The signature is calculated over the encoded header and payload using a key. If anyone changes a single character of the header or payload, the signature no longer matches.

Base64url encoding

The header and payload are not encrypted. They are encoded with Base64url, a variant of Base64 that is safe in URLs (it uses - and _ instead of + and /, and drops = padding). Anyone who has the token can decode and read them — try it with our Base64 encoder and decoder or the JWT decoder.

If you need confidentiality, use an encrypted JWT (JWE) or keep sensitive data on the server and put only an identifier in the token.

Registered claims

RFC 7519 defines a set of standard claim names. None are mandatory in the specification, but most systems use several of them.

ClaimNameMeaning
issIssuerWho created and signed the token
subSubjectWho the token is about, usually a user ID
audAudienceWho the token is intended for, such as your API
expExpiration timeAfter this time the token must be rejected
nbfNot beforeBefore this time the token must be rejected
iatIssued atWhen the token was created
jtiJWT IDA unique identifier, useful for preventing replay

The time claims are NumericDate values: seconds since 1970-01-01 UTC, not milliseconds. Mixing up seconds and milliseconds is a common bug; our timestamp converter shows what a value means. Applications often add their own claims too, such as roles or a tenant ID.

Signing algorithms

HS256 (HMAC with SHA-256)

HS256 uses a single shared secret. The same secret creates and verifies the signature.

  • Simple and fast.
  • Every service that verifies tokens must hold the secret — and anyone with the secret can create valid tokens.
  • The secret must be long and random. Short or guessable secrets can be brute-forced offline from a single captured token.

HS256 suits cases where the same system issues and verifies tokens.

RS256 and ES256 (asymmetric)

RS256 (RSA) and ES256 (elliptic curve) use a key pair. The issuer signs with a private key; anyone can verify with the public key.

  • Services that only verify tokens never hold anything that could create one.
  • Public keys can be published, often as a JSON Web Key Set (JWKS) at a well-known URL, and rotated.

Asymmetric algorithms suit setups with a separate identity provider and many APIs or third parties verifying tokens.

What a server must check

Decoding a token is easy. Validating it is what matters. For every request, a server should:

  1. Verify the signature with the expected key.
  2. Enforce the algorithm. Only accept the algorithm (or short list of algorithms) you actually use. Never let the token’s header decide.
  3. Check exp and reject expired tokens, allowing at most a small clock skew.
  4. Check nbf if present.
  5. Check iss matches the issuer you trust.
  6. Check aud matches your service, so a token issued for one API can’t be used on another.
  7. Apply your own rules, such as required roles or whether the user still exists and is active.

Use a well-maintained library for this, and configure it explicitly with the expected algorithm, issuer and audience. Writing your own JWT verification is rarely a good idea.

Security pitfalls

Accepting “alg: none”

The JWT standards allow an unsecured token with "alg": "none" and no signature. Some early libraries accepted these by default, letting attackers forge any token. Modern libraries reject them unless explicitly allowed. Make sure yours does, and never allow none in production. Our decoder flags tokens that use it.

Algorithm confusion

If a server uses RS256 and its library picks the verification method from the token header, an attacker might send a token labelled HS256 and signed with the server’s public key as if it were an HMAC secret. Vulnerable libraries would accept it. The fix is the same: pin the expected algorithm on the server.

Weak HMAC secrets

A secret like secret123 can be cracked offline quickly once an attacker has one token. Use a long, randomly generated key — at least as many bits as the hash output, for example 256 bits for HS256 — and store it like any other credential. Our hash generator uses the same HMAC primitives if you want to see how signing works.

Long-lived tokens

A JWT is usually valid until it expires, even if the user logs out or their account is disabled, because the server doesn’t look anything up. Keep access tokens short-lived — minutes rather than days — and use a refresh mechanism for longer sessions.

Sensitive data in the payload

As above, the payload is readable by anyone who sees the token: the user, browser extensions, proxies and logs. Keep it to what the receiving service needs.

Logging tokens

Tokens in URLs, logs or analytics can be copied and replayed. Send them in the Authorization header or secure cookies, not query strings, and scrub them from logs.

Revocation and refresh tokens

Because JWTs are self-contained, revoking one before it expires needs extra work. Common approaches:

  • Short access tokens plus refresh tokens. The access token lasts minutes. A longer-lived refresh token, stored more securely and checked against the server, is used to get new access tokens and can be revoked.
  • A deny list of revoked token IDs (jti) checked on each request, which reintroduces a lookup but only for a small list.
  • Token versioning, where a per-user counter in the token must match the current value in the database.

Where to store tokens in the browser

There is no option without trade-offs, and the right choice depends on your architecture.

  • HttpOnly, Secure cookies can’t be read by JavaScript, which protects them from theft through cross-site scripting (XSS). They are sent automatically, so you need protection against cross-site request forgery (CSRF), such as SameSite cookie settings and CSRF tokens where appropriate.
  • Memory (a JavaScript variable) disappears on refresh, so it is usually combined with a refresh token in an HttpOnly cookie.
  • localStorage is simple but readable by any script on the page, so an XSS flaw can leak tokens.

Whatever you choose, preventing XSS is essential: a strict Content Security Policy and careful output escaping protect tokens and everything else on the page. Our website security checklist covers the basics.

When not to use JWTs

JWTs are not automatically better than traditional sessions. For a single website talking to its own backend, a classic server-side session with an opaque session ID in a secure cookie is simpler to revoke and leaks less information. JWTs shine when several services need to verify identity without sharing a session store, or when a separate identity provider issues tokens.

Debugging tokens safely

When something goes wrong — “401 Unauthorized”, “invalid audience”, “token expired” — decode the token and check:

  • Is exp in the past? Remember it is in seconds.
  • Do iss and aud exactly match what the API expects, including trailing slashes?
  • Is alg what the API is configured for?
  • Are the server clocks in sync?

Use test tokens when you can. Decoding in a browser-based tool that sends nothing to a server, like ours, avoids leaking production credentials, but treat real tokens with the same care as passwords.

If you are designing authentication for an app or API, KRA Digital’s backend and API development team can help you choose and implement the right approach. For related terms, see our web development glossary and our guide to encoding, hashing and encryption.

Frequently asked questions

Is a JWT encrypted?

A standard signed JWT is not encrypted. Its header and payload are Base64url-encoded and anyone with the token can read them. The signature only proves the content hasn’t been changed. Use encrypted JWTs (JWE) or keep sensitive data on the server if you need confidentiality.

What is the difference between HS256 and RS256?

HS256 uses one shared secret to sign and verify, so every verifier can also create tokens. RS256 uses a private key to sign and a public key to verify, so verifiers can’t create tokens and public keys can be shared openly.

How long should a JWT last?

Access tokens are commonly kept short-lived, often between a few minutes and an hour, with refresh tokens used to obtain new ones. The right lifetime depends on how sensitive your system is and how you handle revocation.

Can I log someone out with JWTs?

Deleting the token from the client logs that device out, but the token stays valid until it expires unless the server checks a revocation list or token version. Short expiry times and revocable refresh tokens are the usual solution.

Is it safe to decode a JWT online?

Decoding reveals only what is already readable in the token, but pasting a live token into an untrusted website could let someone else use it. Prefer test tokens, and use tools that decode locally in your browser without sending the token anywhere.

Let’s build something great.

Tell us what you want to build, who it is for and what it needs to do. We’ll help you define a practical next step.

Start a project