How JWT Authentication Works: A Developer's Guide
By Álvaro G.V. · Updated
JWT authentication works like this: after login, the server issues a signed token containing claims such as the user ID and an expiry time; the client sends it with every request in an Authorization: Bearer header; and the server checks the signature and the claims instead of looking up a session. The signature makes the token tamper-proof, not secret. This guide covers the structure, how to sign and verify correctly, refresh tokens, the mistakes behind real JWT vulnerabilities, and when sessions are the better choice.
Have a token at hand? Paste it into the client-side JWT decoder to see its header, claims and expiry while you read. It runs in your browser, so the token is never sent to a server.
The Structure of a JWT
A JWT is three Base64url-encoded JSON objects joined by dots:
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.
eyJzdWIiOiJ1c3JfMTIzIiwibmFtZSI6IkFsaWNlIiwiaWF0IjoxNzQzMDMzNjAwLCJleHAiOjE3NDMxMjAwMDB9.
SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c
└── Header ──┘ └───────────────── Payload ──────────────────────┘ └─── Signature ───┘Header
Specifies the token type and signing algorithm:
{
"alg": "HS256",
"typ": "JWT"
}Payload
Contains claims — statements about the user and token metadata:
{
"sub": "usr_123", // Subject: user identifier
"name": "Alice",
"iat": 1743033600, // Issued At (Unix timestamp)
"exp": 1743120000, // Expiration (Unix timestamp)
"role": "admin"
}Standard claim names are defined by the JWT spec: iss (issuer), sub (subject), aud (audience), exp (expiration), nbf (not before), iat (issued at), jti (JWT ID).
Signature
Proves the token hasn't been tampered with:
HMACSHA256(
base64url(header) + "." + base64url(payload),
secret
)The signature covers both the header and payload. If either is modified, the signature becomes invalid. The server can detect any tampering.
Signing a token by hand
There is no magic in a JWT library. This is a complete HS256 token in Node.js, using only the standard library:
const crypto = require("node:crypto");
const secret = process.env.JWT_SECRET; // at least 32 random bytes
const b64url = (obj) => Buffer.from(JSON.stringify(obj)).toString("base64url");
const header = b64url({ alg: "HS256", typ: "JWT" });
const payload = b64url({
sub: "usr_123",
iat: Math.floor(Date.now() / 1000),
exp: Math.floor(Date.now() / 1000) + 15 * 60, // 15 minutes, in SECONDS
});
const signature = crypto
.createHmac("sha256", secret)
.update(`${header}.${payload}`)
.digest("base64url");
const token = `${header}.${payload}.${signature}`;Verification recomputes the HMAC over the first two segments and compares it with the third using a constant-time comparison (crypto.timingSafeEqual). In production, use a maintained library rather than this code; it exists to show that nothing in the token is hidden.
The Authentication Flow
- Login: User sends credentials (username + password) to
POST /auth/login. - Token issuance: Server verifies credentials, creates a JWT signed with its secret key, returns it to the client.
- Authenticated requests: Client includes the JWT in the
Authorizationheader:Authorization: Bearer <token>. - Verification: Server receives the token, verifies the signature using its secret key, checks the
expclaim, and trusts the claims in the payload.
// Step 4 — server-side verification (Node.js)
const jwt = require('jsonwebtoken');
function authenticate(req, res, next) {
const token = req.headers.authorization?.split(' ')[1];
if (!token) return res.status(401).json({ error: 'No token' });
try {
const payload = jwt.verify(token, process.env.JWT_SECRET);
req.user = payload;
next();
} catch (err) {
return res.status(401).json({ error: 'Invalid or expired token' });
}
}What "verify" must check
A signature check alone is not enough. A correct verification step checks, in order:
- The algorithm is one you expect, from your configuration, never from the token's own header.
- The signature with the right key (for RS256/ES256, the key whose
kidmatches, from the issuer's JWKS). expandnbf, with a small clock-skew allowance (30–60 seconds).iss: the token came from your identity provider.aud: the token was issued for this API. Without this check, a token minted for another service of the same provider is accepted by yours.
// Verifying an OpenID Connect access token with the jose library
import { createRemoteJWKSet, jwtVerify } from "jose";
const JWKS = createRemoteJWKSet(new URL("https://auth.example.com/.well-known/jwks.json"));
const { payload } = await jwtVerify(token, JWKS, {
algorithms: ["RS256"],
issuer: "https://auth.example.com/",
audience: "https://api.example.com",
clockTolerance: "30s",
});Access Tokens and Refresh Tokens
Because a JWT can't easily be revoked, most systems keep access tokens short-lived and pair them with a refresh token:
| Access token | Refresh token | |
|---|---|---|
| Typical lifetime | 5–15 minutes | Days to weeks |
| Sent to | Every API request | Only the token endpoint |
| Format | Usually a JWT, verified without a lookup | Often an opaque random string stored server-side |
| Revocation | Wait for expiry (or a denylist) | Delete it from the store |
When the access token expires (the API answers 401), the client calls the refresh endpoint and gets a new pair. With rotation, each refresh token works once: if an old one is presented again, it was probably stolen, so the server revokes the whole token family and the user signs in again. In a browser, keep the refresh token in a cookie scoped to the refresh endpoint:
Set-Cookie: refresh_token=8f3c...; HttpOnly; Secure; SameSite=Strict; Path=/auth/refresh; Max-Age=1209600Why JWTs Are Stateless
Traditional session-based auth stores session data server-side (in memory or a database). The client holds an opaque session ID. On every request, the server looks up the session ID to get user data.
With JWTs, all user information lives in the token itself. The server doesn't need to look anything up — it just verifies the signature and reads the claims. This makes JWTs ideal for:
- Microservices — each service can verify tokens independently without calling an auth service
- Horizontal scaling — no shared session store needed across instances
- Cross-domain authentication — tokens work across different domains; cookies don't (the API still needs the right CORS headers)
HS256 vs RS256 vs ES256
The algorithm choice determines how signing and verification work:
- HS256 (HMAC-SHA256) — symmetric. One shared secret for signing and verifying. Simple, but every verifier can also issue tokens.
- RS256 (RSA-SHA256) — asymmetric. Private key signs, public key verifies. Services can verify without being able to issue tokens.
- ES256 (ECDSA-SHA256) — asymmetric like RS256 but with smaller key sizes and faster operations. Preferred for new systems.
Use HS256 for simple single-service setups. Use RS256 or ES256 when multiple services need to verify tokens (publish your public key as a JWKS endpoint).
Common Security Mistakes
1. Trusting the token's "alg" header
In 2015 several JWT libraries were found to honour whatever algorithm the token declared. Two attacks followed: "alg": "none", which skipped verification entirely, and algorithm confusion, where an attacker changes RS256 to HS256 and signs the token with the server's public key as the HMAC secret. A library that picks the algorithm from the header then verifies the forged token with that same public key. Current versions of mainstream libraries guard against both, but pinning the algorithm costs nothing:
// Relies on library defaults
jwt.verify(token, key);
// Explicit: only RS256 is ever accepted
jwt.verify(token, key, { algorithms: ['RS256'] });2. Not validating exp
Most libraries validate exp automatically, but always confirm yours does. A token without expiry validation is valid forever after theft.
3. Putting sensitive data in the payload
The payload is Base64url-encoded, not encrypted. Anyone with the token can read it, which is also why you shouldn't paste production tokens into online decoders. Only include claims that are safe to expose: user ID, roles, permissions. Never put passwords, PII, or secrets.
4. Calling decode() instead of verify()
jwt.decode() in jsonwebtoken (and similar functions elsewhere) only parses the token; it does not check the signature. Code that reads jwt.decode(token).sub to decide who the user is accepts any token anyone types. Use decode only for display and debugging.
5. Expiry in milliseconds
exp, iat and nbf are Unix timestamps in seconds. Writing exp: Date.now() + 3600 produces a value in milliseconds, which a verifier reads as a date tens of thousands of years in the future, so the token effectively never expires. Use Math.floor(Date.now() / 1000) + 3600, and check a suspicious value with the Unix timestamp converter.
6. Weak HMAC secrets
Anyone holding one HS256 token can try secrets offline at GPU speed (hashcat supports JWTs directly), with no rate limit. Secrets like secret or a project name fall in seconds. Use at least 256 random bits, for example openssl rand -base64 32, or switch to an asymmetric algorithm.
7. Storing JWTs in localStorage
Any XSS vulnerability on your site can read localStorage and steal all tokens. Prefer HttpOnly cookies — JavaScript can't access them.
JWT vs Sessions: When to Use Each
| Concern | JWT | Session |
|---|---|---|
| Instant revocation | Hard (need denylist) | Easy (delete session) |
| Horizontal scaling | Easy (stateless) | Needs shared store |
| Microservices | Great | Complex |
| Payload size | Grows with claims | Fixed (opaque ID) |
| Server storage | None | Required |
For most web apps with a single backend: sessions are simpler and safer by default. For APIs, microservices, or mobile apps: JWTs are the pragmatic choice. Many systems use both — JWTs for stateless API auth, sessions for web browser authentication.
Inspect a JWT right now with the JWT Decoder — paste any token to view its header, payload claims, and expiry status. 100% client-side, your token never leaves the browser.
Frequently Asked Questions
Are JWTs encrypted?▾
By default, no. A standard JWT (JWS — JSON Web Signature) is signed but not encrypted. The header and payload are Base64url-encoded, which anyone can decode instantly. They are not secret. The signature only proves that the token was issued by someone who holds the secret key and hasn't been tampered with. If you need to hide the payload contents, use JWE (JSON Web Encryption), a different spec that encrypts the payload.
Can I invalidate a JWT before it expires?▾
Not directly — this is the biggest drawback of stateless JWTs. Because the server doesn't store session state, it can't 'forget' a token. Common workarounds: (1) Keep a server-side blocklist/denylist of invalidated token JTI (JWT ID) claims. (2) Use short expiry times (15 minutes) and refresh tokens. (3) Change the signing secret to invalidate all tokens at once (nuclear option). Each approach trades some statefulness back into the system.
Where should I store a JWT on the client?▾
localStorage is convenient but vulnerable to XSS — any JavaScript running on your page can read it. An HttpOnly cookie is safer against XSS because JavaScript can't access it, but it's vulnerable to CSRF (mitigated with SameSite=Strict or a CSRF token). For most applications, HttpOnly, Secure, SameSite=Strict cookies are the safer default. Avoid localStorage for tokens that grant access to sensitive operations.
What is the difference between HS256 and RS256?▾
HS256 (HMAC-SHA256) uses a single shared secret for both signing and verification. Everyone who can verify tokens can also create them. RS256 (RSA-SHA256) uses a private key to sign and a public key to verify. The server keeps the private key secret; any service can verify tokens using the public key without being able to issue new ones. Use RS256 in microservices architectures where multiple services need to verify tokens but shouldn't be able to issue them.
Should I put sensitive data in the JWT payload?▾
No. JWT payloads are readable by anyone who has the token — they're Base64url-encoded, not encrypted. Only put non-sensitive claims in the payload: user ID, roles, expiry time. Never put passwords, PII, payment details, or secrets in a JWT payload. If you need to attach sensitive data to a session, use opaque session tokens with server-side storage instead.
Related guides
Why You Should Never Paste Sensitive Data Into Online Tools
API keys, JWT tokens, database URLs, passwords — pasting them into server-side tools is a real security risk. Learn what happens to your data and what client-side alternatives to use.
What Is Base64 Encoding and How Does It Work?
Base64 converts binary data into ASCII text using 64 characters. Learn why it exists, how the encoding works step by step, and when to use it.
CORS Explained: Why It Happens and How to Fix It
CORS errors happen when a browser blocks a request to a different origin. Learn how the Same-Origin Policy works, what preflight requests are, and how to configure CORS correctly in Express, FastAPI, and Nginx.
HTTP Status Codes for REST APIs: 200 vs 201 vs 204, 400 vs 422 vs 429
A practical guide to choosing the right HTTP status code in REST API design. Covers the most confusing pairs: 200 vs 201, 400 vs 422, 401 vs 403, and when to use 503 vs 429.