All articles
165 articles · updated weekly See our Tools
All articles
All

How JWT works: authentication, signing and security

How JWT works in practice: the three parts of the token, what the signature guarantees, HS256 vs RS256, validating iss, aud and exp, and common flaws.

How JWT works: authentication, signing and security
COVER · All

You opened the DevTools of a production app, copied the token it sends with every request, and pasted it into a decoder. Three seconds later you are reading the user's email, the id, the "admin" role, and the expiration date, all in plain text. Nobody gave you permission, nobody needed the key. And that is exactly how JWT was designed to work. The problem is not that the token is readable: it is how many people think it is encrypted.

A JWT (JSON Web Token, RFC 7519) is a compact format for carrying statements (claims) about a user between two parties, signed so the receiver can prove who issued it and that nothing changed along the way. This post explains how JWT works in practice: the three parts of the token, what the signature guarantees, HS256 vs RS256, what the server must validate beyond the signature, and the flaws that still take down APIs. If you want the front-end code side, reading a token in JavaScript without a library, the sibling post is How to decode a JWT in JavaScript without a library.

Anatomy: three parts separated by a dot

A JWT is a string with three Base64URL blocks separated by dots: header.payload.signature. Base64URL is the Base64 variant that swaps + and / for - and _ and drops the = padding, so the token can travel in URLs and HTTP headers without escaping. It is encoding, not encryption — if that distinction is fuzzy, the post on Base64 explains the mechanism, and you can check any block by hand with a Base64 decoder.

The header states which algorithm signs the token and its type:

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

The payload carries the claims, which are statements about the user and about the token itself:

{
  "iss": "https://auth.example.com",
  "aud": "orders-api",
  "sub": "1234567890",
  "name": "Ana Souza",
  "role": "admin",
  "iat": 1721827200,
  "exp": 1721830800
}

The claims registered in RFC 7519 have three-letter names: iss (who issued it), sub (who the token is about), aud (who it was issued for), exp (expiration), nbf (not valid before), iat (issued at) and jti (unique id). Dates are NumericDate: seconds since 1970 in UTC, not milliseconds. The third part, the signature, is the result of signing base64url(header) + "." + base64url(payload) with a key.

You can inspect a token and read its claims with no key at all, which is great for debugging and terrible if you put sensitive data there thinking it was hidden.

What the signature guarantees (and what it does not)

This is where the most common misunderstanding lives. The signature guarantees integrity and authenticity: if someone changes a single character of the payload, the signature no longer matches and the server rejects the token. And it guarantees that whoever issued it held the key. That is all.

The signature does not guarantee confidentiality. Anyone with the token reads the whole payload. The practical rule: never put a password, card number, government id, or any secret in a JWT. Put an id and fetch the rest on the server. If you genuinely need an unreadable payload, there is JWE (JSON Web Encryption, RFC 7516), a different format and rarely what people mean by "JWT".

HS256 vs RS256: shared secret or key pair

The header's alg says how the token was signed, and the choice has architectural consequences.

HS256 is HMAC with SHA-256: a single secret both signs and verifies. Simple and fast, fine when the same service issues and validates. The trouble shows up when several services need to validate: they all need the secret, and any one of them, if compromised, can forge valid tokens.

RS256 is an RSA signature: the private key signs, the public key verifies. The auth server keeps the private key; any microservice validates with the public key without ever being able to forge a token. For distributed systems, federation, or when third parties must validate your tokens (that is the OpenID Connect case, which publishes public keys at a JWKS endpoint), RS256 or ES256 is the sensible choice. Start with HS256 in a monolith; go asymmetric when the topology calls for it.

What the server must validate beyond the signature

A valid signature proves the token was issued by whoever holds the key. It does not prove it was issued for you, nor that it is still valid. RFC 8725 (JWT Best Current Practices, BCP 225, from 2020) lists what a serious verifier does, and this is the part most people skip:

  • Pinned algorithm (section 3.1): the server decides which algorithms it accepts; the header's alg decides nothing.
  • iss (section 3.8): the issuer must be the expected one, and the key used must belong to it.
  • aud (section 3.9): if one issuer mints tokens for several APIs, each API must reject a token that does not carry its name in aud. Without that, a token issued for the reporting service opens the payments service. RFC 7519 is explicit: if the party processing the token does not identify itself with a value in aud, the token must be rejected.
  • exp and nbf: the current time must be before exp and after nbf, with a small leeway for clock skew (the RFC says "usually no more than a few minutes").

In Node, with the jsonwebtoken library (v9), all of that fits in one call:

import jwt from 'jsonwebtoken';

const claims = jwt.verify(token, publicKey, {
  algorithms: ['RS256'],                // never accept the alg from the token
  issuer: 'https://auth.example.com',   // iss
  audience: 'orders-api',               // aud
  clockTolerance: 30,                   // seconds of leeway for exp/nbf
});
// expired token -> TokenExpiredError; wrong iss or aud -> JsonWebTokenError

I ran that snippet with a freshly generated RSA key pair: a valid token passes; a different iss or aud and an expired token are rejected with an explicit error. In Python, PyJWT follows the same design with jwt.decode(token, key, algorithms=["RS256"], audience=..., issuer=...).

The authentication flow in practice

The standard cycle has four steps. The user logs in with credentials. The server validates them, assembles the payload with claims and expiration, signs it, and returns the token. The client stores that token and, on every request, sends it in the header:

GET /api/orders HTTP/1.1
Host: api.example.com
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...

The server verifies the signature and claims and decides whether to authorize, without querying a session database: all the information is inside the token. That is the entire point of JWT and also the source of its biggest problem, revocation. A valid token stays valid until exp; killing a session right now requires reintroducing state (a blocklist, a credential version). That is why the standard pattern is a short access token, 5 to 15 minutes, plus a long-lived refresh token, rotated on every use so that reuse exposes theft. That pair comes from OAuth 2.0, and the post on OAuth shows where it comes from.

Revocation, where to store the token in the browser (an httpOnly cookie or localStorage), and when sessions are simply better than JWT are architecture decisions, and they are broken down in JWT vs sessions: which auth model should you use. If you are designing the API that receives this Bearer, it is also worth reviewing the principles of good REST API design.

The classic security pitfalls

Two vulnerabilities survive because they were born from the format's own design, and both are in section 2 of RFC 8725.

alg: none. RFC 7518 defines an "unsecured" JWS, with alg set to none and an empty signature. A library that honors that value blindly accepts a token where the attacker stripped the signature and edited the payload at will. Mitigation: explicitly require the expected algorithm.

Algorithm confusion (RS256 to HS256). If the server uses RS256 but the library picks the algorithm from the header, the attacker switches alg to HS256 and signs with the public key (which is public) as if it were the HMAC secret. That was exactly the verification bypass fixed in jsonwebtoken 4.2.2 (CVE-2015-9235). I tested the attack against the current v9: it already refuses the forged token with invalid algorithm, even without the algorithms option. Don't count on that in every library and every language; always pass the list of algorithms.

The lesson from both cases is the same: never let the token choose how it will be verified.

Frequently asked questions

What is a JWT, in one sentence?

It is a token in the header.payload.signature format, defined in RFC 7519, where the payload is a JSON object with statements about the user and the signature lets the server confirm who issued it and that nothing changed, without querying a session database.

Is a JWT encrypted?

Not by default. A plain JWT (JWS) is only signed and Base64URL-encoded; anyone with the token reads the payload. The signature protects against tampering, not against reading. An encrypted payload is JWE, a separate and far less used format.

What is the difference between HS256 and RS256?

HS256 is symmetric: the same secret signs and verifies, good for a single service. RS256 is asymmetric: the private key signs and the public key verifies, letting several services validate without being able to forge tokens. For distributed systems or third-party validation, prefer RS256 or ES256.

Which claims must the server validate?

Besides the signature with a pinned algorithm: exp and nbf (with a small clock leeway), iss equal to the expected issuer, and aud containing your API's identifier. Validating only the signature and exp lets through legitimate tokens that were issued for another service.

The token is a signed envelope, not a safe

JWT proves who issued it and that nobody touched the content; it hides nothing. Treat the payload as public, pin the algorithm on the server, validate iss, aud, exp and nbf on every request, and offset the lack of revocation with a short access token and a rotated refresh token. Decode your own tokens once in a while in the JWT decoder: whatever you see in there, everyone else sees too.

RD
Author
Rafael Duarte
Backend developer with a background in fintech and B2B SaaS — worked on teams that scaled APIs from zero to millions of requests. Carries enough production scars to hold strong opinions on tools, patterns and architecture decisions. Not an academic: he read the UUID RFC when he had to choose between v4 and v7 for a write-heavy table.
View profile