JWT Tokens Explained: What They Are and How They Work
JSON Web Tokens (JWTs) are everywhere in modern web development. They power authentication in millions of applications, from single-page apps to mobile backends. Here's everything you need to know.
What Is a JWT?
A JWT is a compact, URL-safe token that represents claims between two parties. It's commonly used for authentication — after a user logs in, the server issues a JWT that the client sends with subsequent requests to prove identity.
A JWT looks like this:
The Three Parts of a JWT
A JWT consists of three Base64URL-encoded parts separated by dots:
1. Header
Contains the token type and signing algorithm:
2. Payload
Contains the claims (data). Common standard claims include:
• sub — Subject (usually user ID)
• iat — Issued at (timestamp)
• exp — Expiration time
• iss — Issuer
• aud — Audience
3. Signature
Created by signing the header and payload with a secret key. This ensures the token hasn't been tampered with.
How JWT Authentication Works
1. User sends credentials (username/password) to the server
2. Server verifies credentials and generates a JWT
3. Server sends the JWT back to the client
4. Client stores the JWT (usually in memory or httpOnly cookies)
5. Client sends the JWT with every subsequent request in the Authorization header
6. Server verifies the JWT signature and extracts user data from the payload
JWT Security Best Practices
1. Always verify the signature — Never trust a JWT without validation
2. Set short expiration times — 15-60 minutes for access tokens
3. Use refresh tokens — Separate long-lived refresh tokens from short-lived access tokens
4. Store tokens securely — httpOnly cookies are safer than localStorage
5. Never put sensitive data in the payload — JWTs are encoded, NOT encrypted
6. Use strong signing keys — At least 256 bits for HMAC algorithms
7. Validate all claims — Check issuer, audience, and expiration
Common JWT Mistakes
1. Storing JWTs in localStorage — Vulnerable to XSS attacks
2. Not validating expiration — Expired tokens should always be rejected
3. Using weak secrets — "secret123" is not a secret
4. Putting passwords in the payload — Anyone can decode the payload
5. Not using HTTPS — JWTs sent over HTTP can be intercepted
