HomeBlogJWT Security Guide: Tokens, Claims, Attacks

JWT Security Guide: Tokens, Claims, Attacks

How JWT works, which signature algorithm to choose, safe storage strategies, and the attack vectors that break real implementations.

DevKit is maintained by hcatree. I wrote the tools on this site and ran the compression benchmarks myself — the script and the raw data download from the benchmarks page.

2026-10-2012 min

What is JWT?

JWT (JSON Web Token, RFC 7519) is a compact, self-contained token format for securely transmitting claims between parties. It consists of three parts separated by dots:

eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjM0NTY3ODkwIn0.Signature
├── Header            ├── Payload            └── Signature
  • Header: Declares the token type (JWT) and signing algorithm (e.g. HS256, RS256)
  • Payload: Contains claim data such as user ID, roles, expiration time, etc.
  • Signature: Signs the Header and Payload using the algorithm specified in the Header, used to verify token integrity

JWT's biggest feature is being self-contained — the token itself carries all necessary information, so the server doesn't need to query a database to verify user identity. This makes JWT especially suitable for microservice architectures and stateless API design.

How JWT Works

A typical JWT authentication flow:

  1. User submits username and password to the authentication server
  2. Server verifies credentials, generates a JWT, and returns it to the client
  3. Client stores the JWT locally (localStorage or HttpOnly Cookie)
  4. Subsequent requests carry the JWT in the Authorization Header: Authorization: Bearer <token>
  5. Server verifies the JWT signature and expiration, processes the request if valid

The key advantage of this flow is being stateless: the server doesn't need to maintain session state, and each request is independent. This is especially important for horizontally scaled distributed systems.

Signature Algorithm Selection

HS256 (Symmetric Signing)

Uses a shared secret key for both signing and verification. Simple to implement, suitable for monolithic applications or internal service communication.

Pros: Simple implementation, fast computation
Cons: Key must be shared among all verifiers; key compromise invalidates all tokens

RS256 (Asymmetric Signing)

Uses a private key for signing and a public key for verification. Suitable for OAuth2/OIDC scenarios requiring multi-party verification.

Pros: Verifiers only need the public key; private key can be strictly guarded
Cons: Slightly more complex implementation, slower than HS256

Algorithm Selection Guide

  • Monolithic apps / Internal services: HS256 is sufficient, simpler key management
  • OAuth2 / OIDC providers: Must use RS256 or ES256
  • Microservice architectures: RS256 recommended, each service only needs the public key
  • Never use alg: none: This completely skips signature verification — a critical security vulnerability

Secure Storage Strategies

How you store JWTs directly impacts application security:

localStorage

// Store
localStorage.setItem('token', jwt);
// Use
const token = localStorage.getItem('token');
fetch('/api/data', { headers: { Authorization: `Bearer ${token}` } });

Risk: Vulnerable to XSS (Cross-Site Scripting) attacks. If an attacker injects malicious scripts, they can read all tokens from localStorage.

HttpOnly Cookie (Recommended)

// Server-side setting
res.cookie('token', jwt, {
  httpOnly: true,    // JavaScript cannot access
  secure: true,      // Only transmitted over HTTPS
  sameSite: 'strict' // Prevents CSRF attacks
});

Advantages: JavaScript cannot read it, naturally immune to XSS token theft. Combined with the SameSite attribute, it effectively defends against CSRF attacks.

Storage Comparison

Storage Method XSS Protection CSRF Protection Difficulty Recommended For
localStorage Poor Naturally immune Low Internal tools, low-risk apps
SessionStorage Poor Naturally immune Low Temporary sessions
HttpOnly Cookie Good Needs extra protection Medium Production (recommended)
Memory (variable) Good Naturally immune Medium SPA applications

Common Attacks and Defenses

1. Token Leakage

Scenario: JWT is leaked through insecure channels (URL parameters, logs).

Defense:

  • Always transmit JWTs over HTTPS
  • Never pass JWTs in URLs
  • Set reasonable expiration times (access tokens: 15-30 minutes recommended)
  • Implement token revocation mechanisms (e.g. Redis blacklist)

2. Algorithm Confusion Attack

Scenario: Attacker changes the algorithm in the Header from RS256 to HS256, then signs using the public key as the HMAC secret.

Defense:

  • Server should enforce the expected algorithm, not accept what the Header declares
  • Explicitly specify the algorithm during verification: jwt.verify(token, secret, { algorithms: ['HS256'] })

3. Sensitive Data Exposure

Scenario: Developers put sensitive information (passwords, ID numbers) in the JWT Payload.

Defense:

  • The Payload is only Base64-encoded, NOT encrypted — anyone can decode and view it
  • Only place necessary claims in the Payload (user ID, roles, expiration)
  • Fetch sensitive data through server-side APIs on demand

JWT vs Session Comparison

Feature JWT Session
State Stateless Stateful (server stores session)
Scalability Excellent (no shared session store needed) Requires session store synchronization
Token Size Larger (carries full claims) Small (session ID only)
Revocation Difficulty Harder (needs blacklist mechanism) Simple (just delete the session)
Cross-domain Support Native support Requires extra configuration
Best For Microservices, mobile APIs, SSO Traditional web apps

Useful Tools

These tools are invaluable when debugging JWTs:

  • JWT Decoding: Use the JWT Decoder to safely inspect token Header and Payload contents in your browser — nothing is sent to any server
  • Security Audit: the JWT Security Audit runs eight checks over one token — alg=none, algorithm confusion, the expiry claims, kid/jku injection, over-long lifetimes, sensitive payload data and a local weak-key dictionary scan — and gives a fix note for every finding
  • Online Debugging: jwt.io provides online decoding, but be careful not to paste production tokens into third-party websites

Understanding and using JWT correctly is fundamental to building secure authentication systems. We hope this guide helps you make smarter technical decisions in your projects.

Discuss this articleEchoForum · no sign-up, replies in any language

Related Tools

JWT DecoderInspect JWT header and payload
JWT Security AuditRun eight security checks on a JWT