Every time you log in to a modern web application and don't have to log in again when you switch tabs or return the next day, JSON Web Tokens (JWT) are likely doing the heavy lifting. JWTs are a compact, self-contained way for securely transmitting information between parties as a JSON object.
This guide digs deep into how JWTs work, their structure, signing algorithms, expiration handling, and the security vulnerabilities you must avoid.
What is a JWT?
A JSON Web Token is a string made up of three Base64url-encoded parts separated by dots:
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkFsaWNlIiwiaWF0IjoxNzE2MDAwMDAwfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5cThe three parts are:
1. Header — Declares the token type and the signing algorithm used
2. Payload — Contains the claims (user data + metadata)
3. Signature — Cryptographic proof that the token hasn't been tampered with
The JWT specification is defined in RFC 7519.
The Header
The header is a JSON object with two standard fields:
{
"alg": "HS256",
"typ": "JWT"
}alg specifies the algorithm used to sign the token:
- HS256 — HMAC with SHA-256 (symmetric — same secret for signing and verification)
- RS256 — RSA with SHA-256 (asymmetric — private key signs, public key verifies)
- ES256 — ECDSA with P-256 (asymmetric — more compact than RSA)
- none — No signature (DANGEROUS — never use in production)
The header is Base64url-encoded, meaning it's readable to anyone — don't put sensitive data in it.
The Payload: Claims
The payload contains claims — statements about the entity (user) and additional metadata.
Registered claims (standardized, optional but recommended):
- iss (Issuer): Who issued the token, e.g., "auth.example.com"
- sub (Subject): Unique identifier of the token subject, e.g., user ID
- aud (Audience): Intended recipient(s)
- exp (Expiration Time): Unix timestamp after which the token is invalid
- iat (Issued At): Unix timestamp when the token was created
- nbf (Not Before): Unix timestamp before which the token must not be accepted
Public claims: Custom fields registered in the IANA JWT Registry
Private claims: Custom fields agreed upon between parties, e.g., {"role": "admin", "plan": "pro"}
⚠️ The payload is Base64url-encoded, not encrypted. Anyone with the token can read the payload. Never store passwords, credit card numbers, or other sensitive data in JWT claims.
The Signature
The signature is what makes JWTs tamper-evident. It is computed by:
HMACSHA256(
base64UrlEncode(header) + "." + base64UrlEncode(payload),
secret
)When a server receives a JWT, it recalculates the signature using the same secret/public key and compares it to the token's signature. If they match, the token is authentic and unmodified. If they don't match — for example, because an attacker changed the role claim from "user" to "admin" — the verification fails.
The signature does NOT encrypt the payload; it only ensures integrity. For confidentiality, use JWE (JSON Web Encryption).
JWT Authentication Flow
Here's the typical server-rendered or SPA authentication flow using JWTs:
1. User logs in: Client sends credentials (username/password) to POST /auth/login
2. Server verifies credentials: Looks up user in the database, hashes and compares the password
3. Server issues JWT: Creates a signed token containing user ID, role, and expiration time
4. Client stores token: Usually in localStorage or an httpOnly cookie
5. Client sends token with requests: Adds Authorization: Bearer <token> header to protected API calls
6. Server validates token: Verifies signature, checks expiration, extracts user info
7. Token refresh: When the access token expires, use a long-lived refresh token to get a new access token without re-authentication
Best practice: Use short-lived access tokens (15 minutes) and long-lived refresh tokens (7-30 days) stored in httpOnly cookies.
Common Security Vulnerabilities
Algorithm confusion (alg:none attack): Older libraries accepted tokens with "alg": "none" and no signature. Always explicitly specify allowed algorithms in your JWT library configuration.
HS256 vs RS256 confusion: If a server uses RS256 and an attacker sends a token with "alg": "HS256" signed with the public key (which is often publicly available), vulnerable servers will accept it. Always pin the expected algorithm.
Weak secrets: HMAC-based JWTs with short or guessable secrets can be brute-forced. Use a randomly generated secret of at least 256 bits.
Missing expiration validation: Always validate the exp claim. A token without expiration can be used indefinitely after a breach.
Storing tokens in localStorage: XSS attacks can steal tokens from localStorage. For high-security apps, store refresh tokens in httpOnly cookies instead.
Token revocation: JWTs are stateless — once issued, they're valid until expiration. Implement a token blocklist (Redis) for immediate revocation if needed.
Choosing Between HS256 and RS256
HS256 (symmetric): The same secret key is used to both sign and verify tokens. Simple to set up, but every service that needs to verify tokens must have the secret. If one service is compromised, all services are at risk.
RS256 (asymmetric): The authentication server signs with a private key. Other services verify with the public key. The public key can be safely distributed (e.g., via a /.well-known/jwks.json endpoint). Even if a service is compromised, only the private key can issue new tokens.
Recommendation: Use RS256 or ES256 in production, especially in microservice architectures where multiple services validate tokens. Use HS256 only for simple, single-server applications.