BlogCommon JWT Vulnerabilities and How to Prevent Them
·11 min read·JWTSecrets Team

Common JWT Vulnerabilities and How to Prevent Them

Covers algorithm confusion, weak secrets, and token leaks with prevention strategies.

Common JWT Vulnerabilities and How to Prevent Them

JWT vulnerabilities have led to critical security breaches. Understanding these attacks is the first step to prevention.

1. Algorithm Confusion (alg:none)

Attackers modify the alg header to none, removing signature verification entirely.

Prevention: Always explicitly specify the expected algorithm on the server side. Never trust the alg header from the token itself.

// WRONG — trusts the token's alg header
jwt.verify(token, secret);

// CORRECT — explicitly specify algorithm
jwt.verify(token, secret, { algorithms: ['HS256'] });

2. Weak Secret Keys

Short or guessable secrets can be brute-forced offline once an attacker captures any token.

Prevention: Use cryptographically random secrets of at least 256 bits (32 bytes).

// Generate a strong secret
const secret = crypto.randomBytes(32).toString('hex'); // 256-bit

3. JWT Header Injection (kid Manipulation)

The kid (Key ID) header can be manipulated to point to attacker-controlled keys or cause SQL injection.

Prevention: Sanitize and validate the kid value. Use an allowlist of valid key identifiers.

4. Token Leakage

Tokens stored in localStorage are accessible to any JavaScript on the page, making them vulnerable to XSS.

Prevention: Store tokens in httpOnly, Secure, SameSite=Strict cookies.

5. Expired Token Acceptance

Failing to validate the exp claim means expired tokens remain valid indefinitely.

Prevention: Always validate expiration. Use short-lived tokens (15 minutes) with refresh token rotation.

6. Missing Audience Validation

Without aud validation, a token issued for one service can be replayed against another.

Prevention: Always set and validate the aud claim.

jwt.verify(token, secret, {
  algorithms: ['HS256'],
  audience: 'https://api.yourservice.com',
  issuer: 'https://auth.yourservice.com',
});