JWT Decoder: Complete Guide to JSON Web Tokens 2025
JWT Decoder: Complete Guide to JSON Web Tokens 2025
JSON Web Tokens (JWT) have become the standard for authentication and authorization in modern web applications. This comprehensive guide covers everything you need to know about JWT tokens and how to decode them.
What is JWT?
JWT (JSON Web Token) is a compact, URL-safe token format used for securely transmitting information between parties. A JWT consists of three parts separated by dots:
1header.payload.signatureJWT Structure:
1. Header - Contains metadata about the token (algorithm, type)
2. Payload - Contains claims (user data, permissions, expiration)
3. Signature - Used to verify token authenticity
Example JWT:
1eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5cJWT Parts Explained
1. Header
The header typically contains:
Decoded Header Example:
1{2 "alg": "HS256",3 "typ": "JWT"4}2. Payload
The payload contains claims (statements about an entity):
Decoded Payload Example:
1{2 "sub": "1234567890",3 "name": "John Doe",4 "iat": 1516239022,5 "exp": 15162426226}3. Signature
The signature is created by:
1. Taking the encoded header and payload
2. Signing them with a secret key
3. Using the algorithm specified in the header
Signature Creation:
1signature = HMACSHA256(2 base64UrlEncode(header) + "." + base64UrlEncode(payload),3 secret4)Why Use JWT?
Advantages:
Common Use Cases:
Decoding JWT Tokens
Manual Decoding (Base64)
JWTs use Base64URL encoding (slightly different from standard Base64):
1function base64UrlDecode(str) {2 // Replace URL-safe characters3 str = str.replace(/-/g, '+').replace(/_/g, '/');4 5 // Add padding if needed6 while (str.length % 4) {7 str += '=';8 }9 10 return atob(str);11}12 13function decodeJWT(token) {14 const parts = token.split('.');15 if (parts.length !== 3) {Using Libraries
JavaScript (Node.js):
1const jwt = require('jsonwebtoken');2 3// Decode without verification (unsafe)4const decoded = jwt.decode(token);5 6// Verify and decode (safe)7const verified = jwt.verify(token, secret);Python:
1import jwt2 3# Decode without verification4decoded = jwt.decode(token, options={"verify_signature": False})5 6# Verify and decode7decoded = jwt.decode(token, secret, algorithms=["HS256"])JWT Claims Explained
Registered Claims (Standard):
Example Claims:
1{2 "iss": "https://codevnexus.com",3 "sub": "user123",4 "aud": "api.codevnexus.com",5 "exp": 1735689600,6 "nbf": 1735686000,7 "iat": 1735686000,8 "jti": "unique-token-id-12345",9 "name": "John Doe",10 "email": "john@example.com",11 "role": "admin",12 "permissions": [13 "read",14 "write",15 "delete"16 ]17}JWT Security Best Practices
1. Always Verify Signatures
Never trust a JWT without verifying its signature:
1// ✗ Bad - Decode without verification2const decoded = jwt.decode(token);3 4// ✓ Good - Verify signature5const decoded = jwt.verify(token, secret, { algorithms: ['HS256'] });2. Use Strong Secrets
Use cryptographically strong, random secrets:
1// ✗ Bad - Weak secret2const secret = 'mySecret';3 4// ✓ Good - Strong secret5const secret = crypto.randomBytes(64).toString('hex');3. Set Expiration Times
Always set reasonable expiration times:
1const token = jwt.sign(payload, secret, {2 expiresIn: '1h', // Token expires in 1 hour3 issuer: 'codevnexus.com',4 audience: 'api.codevnexus.com'5});4. Validate All Claims
Check all relevant claims:
1function validateToken(token) {2 const decoded = jwt.verify(token, secret);3 4 // Check expiration5 if (decoded.exp && decoded.exp < Date.now() / 1000) {6 throw new Error('Token expired');7 }8 9 // Check issuer10 if (decoded.iss !== 'codevnexus.com') {11 throw new Error('Invalid issuer');12 }13 14 // Check audience15 if (decoded.aud !== 'api.codevnexus.com') {5. Use HTTPS Only
Always transmit JWTs over HTTPS:
1// ✗ Bad - HTTP allows token interception2http://api.example.com/protected3 4// ✓ Good - HTTPS encrypts token5https://api.example.com/protected6. Store Tokens Securely
1// ✗ Bad - Local storage (XSS vulnerable)2localStorage.setItem('token', jwt);3 4// ✓ Good - HttpOnly cookies (more secure)5document.cookie = `token=${jwt}; HttpOnly; Secure; SameSite=Strict`;Common JWT Vulnerabilities
1. Algorithm Confusion
Attackers may try to change algorithm to "none":
1// ✓ Prevent algorithm confusion2jwt.verify(token, secret, {3 algorithms: ['HS256'] // Explicitly specify allowed algorithms4});2. Weak Secrets
Weak secrets can be brute-forced:
1// ✗ Bad - Weak secret2const secret = 'password123';3 4// ✓ Good - Strong secret (256+ bits)5const secret = require('crypto').randomBytes(32).toString('hex');3. Token Expiration
Always check expiration:
1const decoded = jwt.decode(token, { complete: true });2const now = Math.floor(Date.now() / 1000);3 4if (decoded.payload.exp && decoded.payload.exp < now) {5 throw new Error('Token expired');6}JWT Implementation Examples
Creating JWT (Node.js)
1const jwt = require('jsonwebtoken');2 3function createToken(user) {4 const payload = {5 sub: user.id,6 name: user.name,7 email: user.email,8 role: user.role9 };10 11 return jwt.sign(payload, secret, {12 expiresIn: '1h',13 issuer: 'codevnexus.com',14 audience: 'api.codevnexus.com'15 });Verifying JWT (Express Middleware)
1function authenticateToken(req, res, next) {2 const authHeader = req.headers['authorization'];3 const token = authHeader && authHeader.split(' ')[1];4 5 if (!token) {6 return res.sendStatus(401);7 }8 9 jwt.verify(token, secret, (err, user) => {10 if (err) return res.sendStatus(403);11 req.user = user;12 next();13 });14}15 JWT Decoder Tools
Online JWT Decoders
Codev Nexus JWT Decoder - Free, instant JWT decoding:
Try it: [codevnexus.com/tools/jwt-decoder](https://codevnexus.com/tools/jwt-decoder)
Command Line Tools
Using jwt-cli:
1npm install -g jwt-cli2jwt decode YOUR_JWT_TOKENUsing jq:
1echo "YOUR_JWT_TOKEN" | cut -d. -f1 | base64 -d | jq2echo "YOUR_JWT_TOKEN" | cut -d. -f2 | base64 -d | jqDebugging JWT Issues
Common Problems:
1. Invalid Token Format: Ensure token has 3 parts separated by dots
2. Expired Token: Check exp claim against current time
3. Invalid Signature: Verify secret key matches
4. Wrong Algorithm: Ensure algorithm matches header
5. Missing Claims: Verify required claims are present
Debugging Steps:
1try {2 const decoded = jwt.verify(token, secret);3 console.log('Token valid:', decoded);4} catch (error) {5 if (error.name === 'TokenExpiredError') {6 console.log('Token expired at:', error.expiredAt);7 } else if (error.name === 'JsonWebTokenError') {8 console.log('Invalid token:', error.message);9 } else {10 console.log('Error:', error.message);11 }12}Conclusion
JWT tokens are essential for modern web authentication. Understanding how to decode, verify, and implement JWTs securely is crucial for building secure applications.
Key Takeaways:
Start using JWT decoders today to understand and debug your authentication tokens!
Resources
Decode JWTs like a pro!
Enjoyed this article?
Support our work and help us create more free content for developers.
Stay Updated
Get the latest articles and updates delivered to your inbox.