What Is JWT
JWT (JSON Web Token) is a compact, URL-safe token format for securely transmitting information between parties. It consists of three parts:
eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjM0In0.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c
|________ Header ________| |________ Payload ________| |________ Signature ________|
Three-Part Structure
| Part | Content | Description |
|------|---------|-------------|
| Header | Algorithm and type | {"alg":"HS256","typ":"JWT"} |
| Payload | Claim data | User info, expiry, etc. |
| Signature | Signature | Verifies token integrity |
Why You Need JWT
- Stateless authentication: Server stores no session info
- Cross-origin support: Naturally supports CORS
- Microservice communication: Securely pass user identity between services
- API access control: Protect API endpoints
- Single Sign-On (SSO): Shared auth state across systems
- Mobile authentication: Ideal for frontend-backend separation
JWT vs Session
| Feature | JWT | Session | |---------|-----|---------| | Storage | Client (Cookie/Header) | Server-side | | Scalability | ✅ Naturally distributed | ❌ Requires shared storage | | Stateless | ✅ No server storage | ❌ Server maintains state | | Logout | ⚠️ Cannot immediately expire | ✅ Server deletes session | | Data exposure | ⚠️ Payload is Base64 only | ✅ Data stays on server |
How to Use an Online Tool
Using DevToolkit Pro's JWT Decoder:
- Paste the JWT token string
- The tool auto-decodes Header and Payload
- Shows human-readable JSON data
- Displays key fields like expiration time
- Supports HS256/RS256 algorithm identification
JWT in Code
Node.js (Generate and Verify)
const jwt = require('jsonwebtoken');
// Generate JWT
const token = jwt.sign(
{ sub: '12345', name: 'Alice', role: 'admin' },
'your-secret-key',
{ expiresIn: '24h' }
);
// Verify JWT
const decoded = jwt.verify(token, 'your-secret-key');
console.log(decoded); // { sub: '12345', name: 'Alice', ... }
Python
import jwt
from datetime import datetime, timedelta
# Generate JWT
payload = {
'sub': '12345',
'name': 'Alice',
'exp': datetime.utcnow() + timedelta(hours=24)
}
token = jwt.encode(payload, 'your-secret-key', algorithm='HS256')
# Verify JWT
decoded = jwt.decode(token, 'your-secret-key', algorithms=['HS256'])
print(decoded)
JWT Security Best Practices
- Use strong secrets: At least 256 bits for HS256
- Set short expiration: 15 minutes to 24 hours
- Use Refresh Tokens: Long-lived refresh mechanism
- Don't store sensitive data: Payload is Base64, not encrypted
- Use HTTPS: Prevent token theft in transit
- Always verify signatures: Validate JWT signature validity
FAQ
Is the JWT Payload Encrypted?
No. JWT Payload is only Base64URL-encoded — anyone can decode and read it. Never store passwords, credit card numbers, or other sensitive data in JWTs. For encryption, use JWE (JSON Web Encryption).
What Happens When JWT Expires?
Use a Refresh Token mechanism. When the Access Token expires, use the Refresh Token to get a new Access Token without re-login.
How Do You Immediately Invalidate a JWT?
Standard JWTs cannot be immediately invalidated (by design — stateless). Solutions: maintain a blacklist (add revoked JWTs to a blocklist), or use short expiration times to reduce the risk window.
This article is brought to you by DevToolkit Pro. More developer tools at the homepage.
相关文章
What Is a CORS Preflight Request (OPTIONS)? A Cross-Origin Mechanism Every Frontend Developer Must Know
What is a CORS preflight request? Why does the browser send an OPTIONS request? This article explains preflight trigger conditions, response headers like Access-Control-Allow-Origin, common CORS error troubleshooting, and how to bypass CORS restrictions in API testing.
Online Certificate Decoder: Parse SSL/TLS Certificate Information
Learn how to use an online tool to decode and view SSL/TLS certificate details. Understand certificate structure, common fields, and how to verify certificate validity.
Complete Guide to HTTP API Testing: From Basics to Advanced Debugging Techniques
Master the core skills of HTTP API testing, including GET/POST/PUT/DELETE requests, header configuration, request body formats, authentication methods, and debugging techniques. Boost your development efficiency with an online API testing tool.