Guide · Developer security
JWT Token Generator Complete Guide
Master JWT token generation with this comprehensive developer guide. Learn structure, algorithms, security best practices, and avoid common pitfalls.
Quick Start: Generate Your First JWT
Need a JWT token right now? Use our JWT Token Generator for instant results.
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5cWhat is a JWT Token?
JSON Web Token (JWT) is a compact, URL-safe means of representing claims between two parties. It's become the industry standard for stateless authentication and authorization in modern web applications.
JWT Advantages
- Stateless - no server storage needed
- Self-contained - includes user info
- URL-safe encoding
- Cross-domain support
- Mobile-friendly
Common Misconceptions
- JWTs are NOT encrypted by default
- NOT suitable for storing sensitive data
- NOT automatically secure
- Size matters - can get large
- Harder to revoke than sessions
JWT Token Structure
Every JWT token consists of three parts separated by dots:
1. Header (Algorithm & Token Type)
{
"alg": "HS256",
"typ": "JWT"
}Specifies the signing algorithm (HS256, RS256, etc.) and token type.
2. Payload (Claims)
{
"sub": "1234567890",
"name": "John Doe",
"iat": 1516239022,
"exp": 1516242622,
"role": "admin"
}Standard Claims:
ississuersubsubjectaudaudienceexpexpirationiatissued atCustom Claims:
- User ID, username
- User roles, permissions
- Custom metadata
- Application-specific data
3. Signature (Security Verification)
HMACSHA256(
base64UrlEncode(header) + "." + base64UrlEncode(payload),
your-256-bit-secret
)Cryptographically signs the header and payload to ensure the token hasn't been tampered with.
JWT Signing Algorithms
Symmetric (HMAC)
- HS256 - Most common, fast, single secret key
- HS384 - Longer hash, more secure
- HS512 - Longest hash, maximum security
Best for: Internal APIs, same organization, simple setup
Asymmetric (RSA/ECDSA)
- RS256 - RSA with SHA-256, widely supported
- ES256 - ECDSA, smaller signatures
- PS256 - RSA-PSS, enhanced security
Best for: Multi-service, public APIs, microservices
Algorithm Selection Guide
Simple AppsUse HS256 for monolithic applicationsMicroservicesUse RS256 for distributed systemsHigh SecurityUse ES256 or PS256 for maximum securityJWT Security Best Practices
Security Essentials
- Always use HTTPS - Prevent token interception
- Set short expiration - Limit damage if compromised
- Validate algorithm - Prevent algorithm confusion
- Use strong secrets - Minimum 256-bit for HS256
- Implement refresh tokens - For long-lived sessions
Security Pitfalls
- Don't store sensitive data - JWTs are readable
- Don't ignore expiration - Always validate 'exp'
- Don't trust user input - Validate all claims
- Don't use 'none' algorithm - Security vulnerability
- Don't store in localStorage - XSS vulnerable
Recommended Token Lifetimes
15minAccess Tokens7 daysRefresh Tokens1 hourAPI Keys24 hoursInternal ServicesCommon JWT Use Cases
Authentication
User login verification and session management
POST /login → JWT with user claimsAuthorization
Role-based access control and permissions
{ "role": "admin", "permissions": ["read", "write"] }Single Sign-On (SSO)
Cross-domain authentication for multiple apps
app1.com ← JWT → app2.comAPI Access
Secure API endpoints and rate limiting
Authorization: Bearer eyJhbGc...Mobile Apps
Stateless authentication for mobile clients
localStorage.setItem('jwt', token)Microservices
Service-to-service authentication
service-mesh auth with RS256Implementation Examples
Node.js with jsonwebtoken
const jwt = require('jsonwebtoken');
// Generate JWT
const token = jwt.sign(
{ userId: 123, role: 'admin' },
process.env.JWT_SECRET,
{ expiresIn: '15m' }
);
// Verify JWT
const decoded = jwt.verify(token, process.env.JWT_SECRET);Python with PyJWT
import jwt
from datetime import datetime, timedelta
# Generate JWT
token = jwt.encode({
'user_id': 123,
'role': 'admin',
'exp': datetime.utcnow() + timedelta(minutes=15)
}, secret_key, algorithm='HS256')
# Verify JWT
decoded = jwt.decode(token, secret_key, algorithms=['HS256'])Frontend JavaScript
// Store JWT
const storeToken = (token) => {
// Secure httpOnly cookie (preferred)
document.cookie = `jwt=${token}; secure; httponly; samesite=strict`;
// Or localStorage (less secure but convenient)
localStorage.setItem('jwt', token);
};
// Send with requests
fetch('/api/protected', {
headers: {
'Authorization': `Bearer ${token}`
}
});Debugging & Testing JWTs
Debugging Tools
jwt.ioOnline JWT decoder and validatorjwt.msJWT analyzer and debuggerBrowser DevToolsNetwork tab to inspect tokensTesting Strategies
Expiration TestingTest tokens with past expiration datesSignature VerificationTest with wrong secrets and algorithmsMalformed TokensTest invalid base64 and JSONCommon JWT Errors
Token expiredCheck 'exp' claim and server timeInvalid signatureVerify secret key and algorithm matchMalformed JWTCheck for proper base64 encodingAdvanced JWT Topics
Refresh Tokens
Long-lived tokens to obtain new access tokens without re-authentication.
- Store securely (httpOnly cookies)
- Implement rotation policy
- Support revocation
JWT Encryption (JWE)
Encrypt JWT payload for additional security when transmitting sensitive data.
- A256GCM encryption
- RSA-OAEP key encryption
- Nested JWT structures
JWT Blacklisting
Revoke JWTs before expiration for security incidents or user logout.
- Redis blacklist cache
- Short expiration times
- JTI (JWT ID) tracking