Skip to main content

Free 30-min security demo  — We'll scan your real code and show live findings, no commitment Book Now

Offensive360
Academy JWT Vulnerabilities
Advanced · 25 min

JWT Vulnerabilities

Explore JWT attacks including the none algorithm bypass, algorithm confusion, and weak secret exploitation.

1 JWT Attacks

JSON Web Tokens are widely used for authentication but are frequently misconfigured. Three critical attack classes exist:

1. Algorithm: none bypass

// Attacker modifies header to: { "alg": "none" }
// Then removes the signature
// Vulnerable servers that accept "none" skip verification!

2. RS256 → HS256 algorithm confusion

When a server uses RS256 (RSA), its public key is often published. An attacker can change the algorithm to HS256 (HMAC) and sign the token with the public key. A vulnerable server that does not pin the expected algorithm will verify this as valid.

import jwt
# Attacker uses the PUBLIC RSA key as the HMAC secret!
token = jwt.encode(payload, public_key, algorithm="HS256")

3. Weak secrets

HS256 tokens signed with guessable secrets (like "secret", "password", or the app name) can be cracked offline using tools like hashcat or jwt-cracker.

2 Secure JWT Implementation

Prevent JWT attacks through strict algorithm pinning, strong secrets, and short expiry times.

Pin the expected algorithm explicitly:

const jwt = require("jsonwebtoken");

// VERIFICATION — always specify algorithms explicitly
try {
  const payload = jwt.verify(token, SECRET, {
    algorithms: ["HS256"],  // Never allow "none" or multiple algorithms
  });
} catch (err) {
  // Token is invalid
}

Strong secrets for HS256:

import secrets
# Generate a 256-bit cryptographically secure secret
JWT_SECRET = secrets.token_hex(32)  # Store in env, not in code

Short expiry + refresh tokens:

const token = jwt.sign(
  { sub: user.id, role: user.role },
  process.env.JWT_SECRET,
  { 
    algorithm: "HS256",
    expiresIn: "15m",  // Short-lived access token
  }
);

Defense checklist:

  • Always specify and pin the expected algorithm in verification
  • Use secrets with at least 256 bits of entropy
  • Set short expiry (15 minutes for access tokens)
  • Implement token revocation for sensitive operations
  • Prefer RS256/ES256 for distributed systems

Knowledge Check

0/3 correct
Q1

How does the "alg: none" JWT attack work?

Q2

In an RS256 to HS256 confusion attack, what does the attacker use as the HMAC signing key?

Q3

What is the most important configuration when calling jwt.verify() to prevent algorithm attacks?

Code Exercise

Secure JWT Verification

The JWT verification below does not pin the algorithm, allowing algorithm confusion attacks. Fix it to explicitly require HS256 only.

javascript