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:
header.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:
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5cJWT Parts Explained
1. Header
The header typically contains:
Decoded Header Example:
{
"alg": "HS256",
"typ": "JWT"
}2. Payload
The payload contains claims (statements about an entity):
Decoded Payload Example:
{
"sub": "1234567890",
"name": "John Doe",
"iat": 1516239022,
"exp": 1516242622
}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:
signature = HMACSHA256(
base64UrlEncode(header) + "." + base64UrlEncode(payload),
secret
)Why Use JWT?
Advantages:
Common Use Cases:
Decoding JWT Tokens
Manual Decoding (Base64)
JWTs use Base64URL encoding (slightly different from standard Base64):
function base64UrlDecode(str) {
// Replace URL-safe characters
str = str.replace(/-/g, '+').replace(/_/g, '/');
// Add padding if needed
while (str.length % 4) {
str += '=';
}
return atob(str);
}
function decodeJWT(token) {
const parts = token.split('.');
if (parts.length !== 3) {Using Libraries
JavaScript (Node.js):
const jwt = require('jsonwebtoken');
// Decode without verification (unsafe)
const decoded = jwt.decode(token);
// Verify and decode (safe)
const verified = jwt.verify(token, secret);Python:
import jwt
# Decode without verification
decoded = jwt.decode(token, options={"verify_signature": False})
# Verify and decode
decoded = jwt.decode(token, secret, algorithms=["HS256"])JWT Claims Explained
Registered Claims (Standard):
Example Claims:
{
"iss": "https://codevnexus.com",
"sub": "user123",
"aud": "api.codevnexus.com",
"exp": 1735689600,
"nbf": 1735686000,
"iat": 1735686000,
"jti": "unique-token-id-12345",
"name": "John Doe",
"email": "john@example.com",
"role": "admin",
"permissions": [
"read",
"write",
"delete"
]
}JWT Security Best Practices
1. Always Verify Signatures
Never trust a JWT without verifying its signature:
// ✗ Bad - Decode without verification
const decoded = jwt.decode(token);
// ✓ Good - Verify signature
const decoded = jwt.verify(token, secret, { algorithms: ['HS256'] });2. Use Strong Secrets
Use cryptographically strong, random secrets:
// ✗ Bad - Weak secret
const secret = 'mySecret';
// ✓ Good - Strong secret
const secret = crypto.randomBytes(64).toString('hex');3. Set Expiration Times
Always set reasonable expiration times:
const token = jwt.sign(payload, secret, {
expiresIn: '1h', // Token expires in 1 hour
issuer: 'codevnexus.com',
audience: 'api.codevnexus.com'
});4. Validate All Claims
Check all relevant claims:
function validateToken(token) {
const decoded = jwt.verify(token, secret);
// Check expiration
if (decoded.exp && decoded.exp < Date.now() / 1000) {
throw new Error('Token expired');
}
// Check issuer
if (decoded.iss !== 'codevnexus.com') {
throw new Error('Invalid issuer');
}
// Check audience
if (decoded.aud !== 'api.codevnexus.com') {5. Use HTTPS Only
Always transmit JWTs over HTTPS:
// ✗ Bad - HTTP allows token interception
http://api.example.com/protected
// ✓ Good - HTTPS encrypts token
https://api.example.com/protected6. Store Tokens Securely
// ✗ Bad - Local storage (XSS vulnerable)
localStorage.setItem('token', jwt);
// ✓ Good - HttpOnly cookies (more secure)
document.cookie = `token=${jwt}; HttpOnly; Secure; SameSite=Strict`;Common JWT Vulnerabilities
1. Algorithm Confusion
Attackers may try to change algorithm to "none":
// ✓ Prevent algorithm confusion
jwt.verify(token, secret, {
algorithms: ['HS256'] // Explicitly specify allowed algorithms
});2. Weak Secrets
Weak secrets can be brute-forced:
// ✗ Bad - Weak secret
const secret = 'password123';
// ✓ Good - Strong secret (256+ bits)
const secret = require('crypto').randomBytes(32).toString('hex');3. Token Expiration
Always check expiration:
const decoded = jwt.decode(token, { complete: true });
const now = Math.floor(Date.now() / 1000);
if (decoded.payload.exp && decoded.payload.exp < now) {
throw new Error('Token expired');
}JWT Implementation Examples
Creating JWT (Node.js)
const jwt = require('jsonwebtoken');
function createToken(user) {
const payload = {
sub: user.id,
name: user.name,
email: user.email,
role: user.role
};
return jwt.sign(payload, secret, {
expiresIn: '1h',
issuer: 'codevnexus.com',
audience: 'api.codevnexus.com'
});Verifying JWT (Express Middleware)
function authenticateToken(req, res, next) {
const authHeader = req.headers['authorization'];
const token = authHeader && authHeader.split(' ')[1];
if (!token) {
return res.sendStatus(401);
}
jwt.verify(token, secret, (err, user) => {
if (err) return res.sendStatus(403);
req.user = user;
next();
});
}
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:
npm install -g jwt-cli
jwt decode YOUR_JWT_TOKENUsing jq:
echo "YOUR_JWT_TOKEN" | cut -d. -f1 | base64 -d | jq
echo "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:
try {
const decoded = jwt.verify(token, secret);
console.log('Token valid:', decoded);
} catch (error) {
if (error.name === 'TokenExpiredError') {
console.log('Token expired at:', error.expiredAt);
} else if (error.name === 'JsonWebTokenError') {
console.log('Invalid token:', error.message);
} else {
console.log('Error:', error.message);
}
}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!
Share this article
Help others discover this content
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.