正在加载,请稍候…

What Is JWT? How JSON Web Tokens Work (With Examples)

A complete beginner-to-advanced guide to JWT: what it is, how the three parts work, when to use it vs sessions, and common security pitfalls to avoid.

What Is a JWT?

A JSON Web Token (JWT) is a compact, URL-safe string used to transmit verified claims between two parties. Think of it as a signed digital ticket: the server issues it, the client stores it, and every subsequent request presents it as proof of identity.

JWTs are self-contained — the token itself carries the data you need, so the server doesn't have to look anything up in a database on every request.

The Three Parts of a JWT

A JWT looks like this:

xxxxx.yyyyy.zzzzz

Split by dots, you get three Base64URL-encoded sections:

1. Header

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

Declares the token type and the signing algorithm. Common algorithms: HS256 (HMAC-SHA256, symmetric), RS256 (RSA, asymmetric), ES256 (ECDSA).

2. Payload (Claims)

{
  "sub": "user_123",
  "name": "Alice",
  "role": "admin",
  "iat": 1716825600,
  "exp": 1716829200
}

Contains the actual data ("claims"). Standard registered claims:

Claim Meaning
sub Subject (user ID)
iss Issuer
aud Audience
exp Expiration time (Unix timestamp)
iat Issued at
nbf Not before

Important: The payload is only Base64URL-encoded, not encrypted. Anyone can decode it. Never put passwords or sensitive PII in the payload.

3. Signature

HMACSHA256(
  base64UrlEncode(header) + "." + base64UrlEncode(payload),
  secret
)

The signature verifies that the token hasn't been tampered with. If any bit of the header or payload changes, the signature becomes invalid.

How JWT Authentication Works (Step by Step)

1. User sends credentials (username + password) to POST /login
2. Server validates credentials
3. Server creates JWT with user claims, signs it with secret
4. Server returns JWT to client
5. Client stores JWT (memory, localStorage, httpOnly cookie)
6. Client sends JWT in every request: Authorization: Bearer <token>
7. Server validates signature on every request — no DB lookup needed
8. Server reads claims from payload directly

JWT vs Session Tokens

Factor JWT Sessions
Storage Client-side Server-side (DB/Redis)
Scalability Stateless, easy to scale Requires sticky sessions or shared store
Revocation Hard (must wait for expiry) Easy (delete from store)
Payload Carries data Only an opaque ID
Size Larger (~500 bytes+) Small (16–32 bytes)
Best for APIs, microservices Monolithic web apps

Rule of thumb: Use sessions for traditional web apps where you need instant logout. Use JWTs for APIs and distributed systems.

Common JWT Security Mistakes

1. Using "alg: none"

Some early libraries accepted unsigned tokens when alg was set to "none". Always explicitly validate the algorithm:

jwt.verify(token, secret, { algorithms: ['HS256'] });

2. Storing JWTs in localStorage

localStorage is accessible via JavaScript, making it vulnerable to XSS. Prefer httpOnly cookies for browser-based apps.

3. Symmetric key shared between services

With HS256, every service needs the same secret to verify tokens — meaning any service can also issue tokens. Use RS256/ES256 so only the auth service has the private key; other services only need the public key.

4. Long expiry times with no refresh

A 30-day JWT that can't be revoked is a security liability. Pattern to follow:

  • Access token: short-lived (15 min)
  • Refresh token: long-lived (7–30 days), stored in httpOnly cookie, rotated on each use

5. Not validating exp

Always verify the expiry. Most libraries do this automatically, but confirm it's not disabled.

Decoding a JWT Without a Library

function decodeJwt(token) {
  const [headerB64, payloadB64] = token.split('.');
  const decode = (str) => JSON.parse(atob(str.replace(/-/g, '+').replace(/_/g, '/')));
  return {
    header: decode(headerB64),
    payload: decode(payloadB64),
  };
}

const { payload } = decodeJwt(myToken);
console.log(payload.sub); // user_123

Frequently Asked Questions

Q: Can I use JWT without HTTPS? No. Always use HTTPS. Without TLS, tokens can be intercepted and reused (replay attacks).

Q: How do I invalidate a JWT before it expires? Options: maintain a server-side blacklist/denylist, use short expiry + refresh tokens, or change the signing secret (invalidates all tokens).

Q: What's the maximum size for a JWT payload? No hard limit, but keep it small (under 1 KB). Larger tokens increase request overhead. Avoid storing anything you'd look up from a database on every request.

Q: Is JWT the same as OAuth? No. JWT is a token format. OAuth 2.0 is an authorization protocol that can use JWTs as its token format.

→ Inspect and decode any JWT token with the JWT Parser.