Understanding JWT Structure
A JWT consists of three parts separated by dots: header, payload, and signature.
Format
xxxxx.yyyyy.zzzzz- Header: Contains metadata about the token
- Payload: Contains the claims (data)
- Signature: Verifies the token's authenticity
The Header
The header typically contains the type of token and the signing algorithm.
Example Header
{
"alg": "HS256",
"typ": "JWT"
}Fields
- alg: Algorithm used for signing (HS256, RS256, etc.)
- typ: Token type (usually "JWT")
The Payload
The payload contains claims, which are statements about an entity and additional data.
Registered Claims
{
"sub": "1234567890",
"name": "John Doe",
"iat": 1516239022,
"exp": 1516242622
}Common Claims
- iss: Issuer of the token
- sub: Subject of the token
- aud: Audience of the token
- exp: Expiration time
- nbf: Not before time
- iat: Issued at time
- jti: JWT ID
The Signature
The signature is created by signing the encoded header and payload with a secret.
Creation Process
HMACSHA256(
base64UrlEncode(header) + "." + base64UrlEncode(payload),
secret
)The signature ensures the token hasn't been tampered with.
JWT vs Session Cookies
JWT Benefits
- Stateless: No server-side storage needed
- Scalable: Easy to distribute across servers
- Cross-domain: Works across different domains
- Mobile-friendly: Easy to use in mobile apps
Session Cookies Benefits
- Server-controlled: Can be invalidated instantly
- Smaller: Only a session ID
- More secure: Less exposed to XSS
Use Cases
Authentication
User logs in, server returns JWT, client includes JWT in subsequent requests.
Authorization
JWT contains user roles/permissions, server validates on each request.
Information Exchange
Securely transmit information between services.
Single Sign-On
Enable SSO across multiple applications.
Security Best Practices
Strong Secret Keys
Use long, random secrets for HMAC signing.
Short Expiration
Set reasonable expiration times (e.g., 15-30 minutes for access tokens).
HTTPS Only
Always transmit JWTs over HTTPS to prevent interception.
Validate Everything
Always validate signature, expiration, and issuer on the server.
Refresh Tokens
Use refresh tokens to get new access tokens without re-authentication.
Common Algorithms
HS256 (HMAC SHA-256)
Symmetric algorithm using a shared secret. Fast and simple.
RS256 (RSA SHA-256)
Asymmetric algorithm using public/private key pair. More secure for distributed systems.
ES256 (ECDSA SHA-256)
Asymmetric algorithm using elliptic curve cryptography. More efficient than RSA.
Token Storage
LocalStorage
Easy to use but vulnerable to XSS.
SessionStorage
Similar to localStorage but cleared on tab close.
Cookies
More secure with HttpOnly and SameSite flags.
Memory
Most secure but lost on page refresh.
Validation Process
Step 1: Decode
Base64 decode the header and payload.
Step 2: Verify Signature
Recreate the signature and compare with the token's signature.
Step 3: Check Claims
Validate expiration, issuer, audience, and other claims.
Step 4: Use Data
Extract and use the claims from the payload.
Common Pitfalls
Storing Sensitive Data
Never store passwords or secrets in JWT payload.
Long-Lived Tokens
Avoid tokens with long expiration times.
Ignoring Validation
Always validate tokens on the server.
Weak Secrets
Use strong, random secrets for signing.
No Revocation
JWTs are hard to revoke; implement a blacklist if needed.
Implementing JWT in Applications
Node.js with jsonwebtoken
const jwt = require('jsonwebtoken');
// Generate
const token = jwt.sign({ userId: 123 }, 'secret', { expiresIn: '1h' });
// Verify
const decoded = jwt.verify(token, 'secret');Python with PyJWT
import jwt
# Generate
token = jwt.encode({'user_id': 123}, 'secret', algorithm='HS256')
# Verify
decoded = jwt.decode(token, 'secret', algorithms=['HS256'])Token Refresh Strategy
Access Token + Refresh Token
- Access token: Short-lived (15-30 minutes)
- Refresh token: Long-lived (days/weeks)
- Use refresh token to get new access token
Sliding Expiration
- Extend token expiration on each use
- Set maximum lifetime for security
Debugging JWTs
Use jwt.io
Paste your token to decode and inspect it.
Check Signature
Verify the signature matches your secret.
Validate Claims
Ensure all claims are valid and not expired.
Test with Different Libraries
Verify token works across different implementations.
Advanced Topics
Custom Claims
Add application-specific claims to the payload.
Nested Tokens
Use tokens within tokens for complex scenarios.
Token Binding
Bind tokens to specific devices or sessions.
Encrypted JWTs (JWE)
Encrypt the entire token for additional security.
The JWT Generator tool simplifies the process of creating and understanding JSON Web Tokens. Whether you're implementing authentication, authorization, or secure information exchange, understanding JWT fundamentals is essential for modern web development. Start using the generator today to create your JWTs.