Back to cheatsheets
Cryptography
JWT Decoding & Security
Decode JWT header and payload, detect alg:none attacks, and validate token expiry — all client-side.
What you'll learn
- Decode JWT
- Security checks
How to use these snippets
- Click the Copy button next to any snippet to copy it to your clipboard.
- Paste the code into your project, IDE, or terminal.
- Replace placeholder values (like
example.comoryour-secret) with your actual data. - Review the code comments for important security notes and caveats.
- Try the interactive related tool to see the concept in action.
Code Snippets
Copy-paste code snippets
2 ready-to-use snippets for jwt decoding & security. Click copy and paste into your project.
Decode JWT
function decodeJWT(token) {
const parts = token.split('.');
if (parts.length !== 3)
throw new Error('Invalid JWT format');
const decode = (str) => {
// Base64url → Base64
str = str.replace(/-/g, '+').replace(/_/g, '/');
// Pad
while (str.length % 4) str += '=';
return JSON.parse(atob(str));
};
return {
header: decode(parts[0]),
payload: decode(parts[1]),
signature: parts[2],
};
}
Security checks
function auditJWT(token) {
const { header, payload } = decodeJWT(token);
const issues = [];
// alg:none attack
if (header.alg === 'none')
issues.push('CRITICAL: alg:none — token is unsigned');
// Weak algorithm
if (header.alg === 'HS256')
issues.push('Warning: HS256 — ensure strong secret');
// Expiry check
if (payload.exp) {
const expired = Date.now() / 1000 > payload.exp;
if (expired) issues.push('Token expired');
}
// Not yet valid
if (payload.nbf && Date.now() / 1000 < payload.nbf)
issues.push('Token not yet valid');
return issues;
}
Tool
Related ShieldX tool
Try this concept hands-on with the interactive tool.
100% Free · No signup · No cost
Generate something unguessable right now
148 bits of entropy, a crack-time estimate you can trust, and a clipboard that clears itself after 30 seconds.
Part of the Toolly ecosystem · secure.toolly.site