14 min read

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.

Example JWT
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c

What 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)

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

Specifies the signing algorithm (HS256, RS256, etc.) and token type.

2. Payload (Claims)

Payload
{
  "sub": "1234567890",
  "name": "John Doe",
  "iat": 1516239022,
  "exp": 1516242622,
  "role": "admin"
}

Standard Claims:

ississuer
subsubject
audaudience
expexpiration
iatissued at

Custom Claims:

  • User ID, username
  • User roles, permissions
  • Custom metadata
  • Application-specific data

3. Signature (Security Verification)

Signature
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 applications
MicroservicesUse RS256 for distributed systems
High SecurityUse ES256 or PS256 for maximum security

JWT Security Best Practices

Security Essentials

Do:
  • 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:
  • 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 Tokens
7 daysRefresh Tokens
1 hourAPI Keys
24 hoursInternal Services

Common JWT Use Cases

Authentication

User login verification and session management

POST /login → JWT with user claims

Authorization

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.com

API 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 RS256

Implementation Examples

Node.js with jsonwebtoken

Node.js
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

Python
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

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 validator
jwt.msJWT analyzer and debugger
Browser DevToolsNetwork tab to inspect tokens

Testing Strategies

Expiration TestingTest tokens with past expiration dates
Signature VerificationTest with wrong secrets and algorithms
Malformed TokensTest invalid base64 and JSON

Common JWT Errors

Token expiredCheck 'exp' claim and server time
Invalid signatureVerify secret key and algorithm match
Malformed JWTCheck for proper base64 encoding

Advanced 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