JSON Web Tokens: Header, Claims, and Signature
Table of Contents
1. JSON Web Token
A JWT consists of three parts separated by dots: header.payload.signature
1.1. Header
The header specifies the token type and signing algorithm:
{
"typ": "JWT",
"alg": "HS256"
}
Common algorithms:
HS256- HMAC with SHA-256 (symmetric)RS256- RSA with SHA-256 (asymmetric)ES256- ECDSA with P-256 curve
1.2. Claims Set (Payload)
The payload contains claims about the entity and additional metadata:
{
"sub": "1234567890",
"name": "Alice",
"email": "alice@example.com",
"iat": 1516239022,
"exp": 1516242622,
"roles": ["user", "admin"]
}
1.2.1. Registered Claims
| Claim | Description |
|---|---|
| iss | Issuer |
| sub | Subject (user ID) |
| aud | Audience |
| exp | Expiration time |
| nbf | Not before |
| iat | Issued at |
| jti | JWT ID (unique token ID) |
1.3. Signature
The signature is created by encoding header and payload, then signing:
HMACSHA256( base64UrlEncode(header) + "." + base64UrlEncode(payload), secret )
1.4. Example Token
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9. eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkFsaWNlIiwiaWF0IjoxNTE2MjM5MDIyfQ. SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c
2. Implementation
2.1. Python
import jwt from datetime import datetime, timedelta secret = "your-secret-key" # Create token payload = { "sub": "user123", "exp": datetime.utcnow() + timedelta(hours=1) } token = jwt.encode(payload, secret, algorithm="HS256") # Verify token decoded = jwt.decode(token, secret, algorithms=["HS256"])
2.2. JavaScript
const jwt = require('jsonwebtoken'); const secret = 'your-secret-key'; // Create token const token = jwt.sign({ userId: '123' }, secret, { expiresIn: '1h' }); // Verify token const decoded = jwt.verify(token, secret);
3. Security Considerations
- Always validate
expclaim - Use strong secrets (256+ bits)
- Prefer RS256 for distributed systems
- Never store sensitive data in payload
- Implement token revocation for logout
5. Related
- Token-Based Authentication in Web Frameworks — Comparative analysis of JWT Auth (Laravel) vs Devise Token Auth (Rails), covering token lifecycle, revocation, and storage tradeoffs