Problem Framing: Why JWTs Still Matter (and Why They Get Attacked)
JSON Web Tokens (JWTs) have become a ubiquitous standard for securely transmitting information between parties, particularly in the realm of authentication and authorization. Their popularity stems from their stateless nature, allowing for scalable architectures where servers don't need to maintain persistent session state. However, this very statelessness and the self-contained nature of JWTs also present significant security challenges. When implemented improperly, JWTs can become a critical attack vector, leading to unauthorized access, privilege escalation, and complete system compromise.
At their core, JWTs are simply base64url-encoded JSON objects containing a header, a payload (claims), and a signature. While the header specifies metadata like the signing algorithm, and the payload carries verifiable statements about an entity (e.g., user ID, roles, expiration), it's the signature that is supposed to guarantee the integrity and authenticity of the token. The security of the entire system often hinges on the correct implementation of signature verification and the secure management of the underlying cryptographic keys. Unfortunately, common implementation oversights and misunderstandings of the JWT specification have led to a persistent stream of vulnerabilities.
This guide aims to provide a deep dive into the practical aspects of JWT security for experienced application security professionals. We'll explore the fundamental mechanics, common attack vectors, detection strategies, and robust prevention measures. Understanding these nuances is critical for building and securing systems that rely on JWTs for authentication and authorization.
Core Mechanics: Structure, Signing, and Verification
A JWT is fundamentally a string composed of three parts, separated by dots (.), each base64url-encoded:
- Header: Contains metadata about the token, most importantly the signing algorithm (
alg) and token type (typ). For example:{"alg": "HS256", "typ": "JWT"}[1][2]. - Payload: Contains the claims, which are statements about an entity (typically the user) and additional data. These can be registered claims (like
issfor issuer,expfor expiration,audfor audience), public claims, or private claims. For example:{"sub": "1234567890", "name": "John Doe", "admin": true}[3][2]. - Signature: Generated by taking the encoded header, the encoded payload, and a secret or private key, and applying the algorithm specified in the header. This signature ensures the token has not been tampered with and was issued by the expected party. The signature is also base64url-encoded [2][1].
The overall structure is base64UrlEncode(header) + "." + base64UrlEncode(payload) + "." + base64UrlEncode(signature).
Signing Process (Simplified):
signature = ALGORITHM.Sign( base64UrlEncode(header) + "." + base64UrlEncode(payload), secretOrPrivateKey )
Verification Process (Simplified):
# 1. Decode header and payload header = base64UrlDecode(token.split('.')[0]) payload = base64UrlDecode(token.split('.')[1])
# 2. Determine algorithm from header algorithm = header.get('alg')
# 3. Verify signature using the algorithm and the secret/public key is_valid = ALGORITHM.Verify( base64UrlEncode(header) + "." + base64UrlEncode(payload), token.split('.')[2], # The signature secretOrPublicKey, algorithm=algorithm # Crucially, THIS MUST BE TRUSTED AND PINNED )
# 4. If valid, trust the payload if is_valid: # Process payload claims (exp, aud, iss, etc.) process(payload)
The critical point of failure often lies in step 3, specifically in how the algorithm is determined and how the secretOrPublicKey is used. Vulnerabilities arise when the application blindly trusts the alg value from the header or improperly handles cryptographic keys.
Notable Techniques and Attack Vectors
JWT vulnerabilities exploit weaknesses in implementation, cryptographic choices, and trust assumptions. The most prevalent attack vectors target signature verification and algorithm handling.
1. Signature Verification Failures
This is arguably the most common and impactful category of JWT vulnerabilities. It occurs when the server fails to properly validate the signature on an incoming token.
- Using
decode()instead ofverify(): Many JWT libraries offer distinct functions for merely decoding the token's contents and for verifying the signature before decoding. Developers may mistakenly use a decoding-only function, completely bypassing signature validation. [1][8][9][10] - The "None" Algorithm (
alg: "none"): The JWT standard permits an algorithm value of "none", indicating an unsigned token. Vulnerable implementations that don't explicitly reject this algorithm, or have case-insensitive checks that can be bypassed (e.g.,None,NONE), will accept tokens with no signature. Attackers can simply remove the signature part and set the algorithm to "none" to forge tokens. [6][1][11][12][13][14][9][15][10][16] - Null Signature/Signature Stripping: Similar to the "none" algorithm, some implementations might accept tokens with an empty signature, even if the
algheader is not explicitly set to "none". This can happen if the verification logic doesn't correctly handle a missing or empty signature as an error. [17][18][15][10]
# Example of crafting a 'none' algorithm token (manually or with a tool) # Original token: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIn0.signature_here # Modified token: eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkFkbWluIn0.
2. Algorithm Confusion Attacks
These attacks exploit the server's trust in the alg parameter specified in the JWT header. Instead of enforcing a specific, expected algorithm server-side, the vulnerable server uses the algorithm provided in the token header to select the verification method.
- RS256 to HS256 Confusion: This is the most common algorithm confusion attack. An attacker crafts a token with the
algheader set to HS256 (symmetric HMAC) instead of RS256 (asymmetric RSA). The attacker then signs this token using the server's public RSA key as the HMAC secret. Since the public key is often publicly accessible (e.g., via a JWKS endpoint), the attacker can generate a valid signature that the server, trusting the HS256 header, will verify using the public key as an HMAC secret. [6][19][20][21][22][23][1][11][24][25][26][27][13][28][4][29][30][31][9][15][32][33][10] - ECDSA to HS256 Confusion: Similar to the RS256 to HS256 attack, but applicable when the server uses ECDSA for signing. The attacker sets the
algto HS256 and uses the server's public ECDSA key as the HMAC secret. [23][34][13][4][31][33] - Unknown Algorithm Bypass: Some JWT libraries might not properly validate the
algvalue. If an attacker provides an unrecognized algorithm string (e.g., "zzz", "banana"), the library might default to a bypass or an insecure verification mechanism, such as returning an empty signature or treating it as unsigned. [35][25][13]
# Example of crafting an HS256 token signed with an RSA public key # (Requires attacker to obtain the server's public key and use a tool like jwt_tool or custom script) # Original header: {"alg": "RS256", "typ": "JWT", "kid": "some-key-id"} # Modified header: {"alg": "HS256", "typ": "JWT", "kid": "some-key-id"} # Payload: {"sub": "attacker", "admin": true} # Signature: Generated using HMAC-SHA256 with the server's public key as the secret.
3. Weak Secrets and Key Management
For symmetric algorithms like HS256, HS384, and HS512, the security relies entirely on the secrecy and strength of the shared secret key. Weak or compromised keys are a direct path to token forgery.
- Guessable Secrets: Developers often use predictable secrets like "secret", "password123", "changeme", or application-specific names. These are easily brute-forced or dictionary-attacked offline. [36][11][37][27][4][38][39][40][15][41][42][32][10][43]
- Hardcoded Secrets: Secrets embedded directly in client-side code (e.g., JavaScript) or committed to version control systems are highly vulnerable. [2][37]
- Key Rotation Neglect: Failure to regularly rotate signing keys leaves tokens vulnerable for extended periods if a key is compromised. [44][37]
- Insufficient Entropy: Using keys that are too short or lack sufficient randomness drastically weakens cryptographic strength. [45][37]
# Example using jwt_tool to crack an HS256 token with a weak secret # python3 jwt_tool.py <JWT_TOKEN> -C -d /path/to/wordlist.txt
4. Header Parameter Injection and Manipulation
Certain JWT header parameters, if not properly validated by the server, can be manipulated to achieve various attacks.
kid(Key ID) Injection: Thekidparameter specifies which key to use for signature verification. If the server uses this value to construct file paths or database queries without sanitization, it can lead to path traversal or SQL injection vulnerabilities. Attackers can pointkidto sensitive files (e.g.,/dev/null, system configuration files) and use their contents as a signing key, or even achieve command injection. [7][46][47][48][49][50][51][52][32]jku(JWK Set URL) andx5u(X.509 URL) Injection: These parameters specify URLs from which to fetch the public key or certificate for verification. If not strictly validated against an allowlist, an attacker can host their own JWKS file at a controlled URL, containing their own public key. The server then fetches this malicious key and verifies a token signed by the attacker's private key. [46][29][53][30][54][55][32][33]jwk(JSON Web Key) Injection: This parameter allows embedding the public key directly within the JWT header. Vulnerable implementations might trust this embedded key for verification, allowing an attacker to embed their own key and sign a forged token. [17][54][55][56]
# Example of kid path traversal to /dev/null # Original header: {"alg": "HS256", "typ": "JWT", "kid": "some_actual_key_id"} # Modified header: {"alg": "HS256", "typ": "JWT", "kid": "../../../../../../../proc/self/getPrototypeOf"}
5. Claim Tampering and Validation Issues
Even if the signature is valid, the claims within the payload must be correctly validated by the server.
- Missing or Incorrect Claim Validation: Critical registered claims like
exp(expiration),nbf(not before),iss(issuer), andaud(audience) must be validated. - Expiration Bypass: If
expis not checked, a valid token can be used indefinitely. [57][36][58][44][37][5][9][15][10][16] - Issuer (
iss) Validation Failure: If theissclaim is not validated against a trusted issuer, tokens from other, potentially malicious, issuers might be accepted. [36][58][59][60][13][61][62] - Audience (
aud) Validation Failure: If theaudclaim is not validated, tokens intended for one service might be replayed against another, potentially granting unintended access. [36][58][60][5][13][63][61][62][64] - Partial Claim Matching: Vulnerabilities in validation logic might allow partial string matches for claims like
issoraud, enabling spoofing. [59] - Sensitive Data in Payload: Storing sensitive information (passwords, PII, credit card numbers) directly in the JWT payload is a critical security flaw, as JWTs are typically only encoded, not encrypted. Anyone intercepting or obtaining the token can read this data. [2][11][60][5][65][66][67][68][16]
- Token Replay: Without proper mechanisms like short expiration times,
jti(JWT ID) claims, or checkingnbf, attackers can reuse captured tokens. [69][44][37][5][9][16]
6. Client-Side Storage Vulnerabilities
How JWTs are stored on the client-side significantly impacts security, particularly against Cross-Site Scripting (XSS) attacks.
- Storing JWTs in
localStorage/sessionStorage: These browser storage mechanisms are accessible via JavaScript, making them vulnerable to XSS attacks. If an XSS vulnerability exists, attackers can steal tokens stored here. [57][70][36][5][71][16] - Cookie Storage without
HttpOnlyandSecureflags: While cookies are generally preferred, if not properly configured withHttpOnly(to prevent JavaScript access) andSecure(to ensure transmission over HTTPS), they can still be vulnerable. [36][5][61]
7. Other Vulnerabilities
- Key Injection via
kid: Beyond path traversal, if thekidvalue is used in database queries, it can be vulnerable to SQL injection. [65][50] - JWE Processing Issues: When JWTs are encrypted (JWE), vulnerabilities can arise if the inner signature is not validated after decryption, allowing unsigned inner JWTs to be accepted. [72][73][74]
- Weak Encryption/Key Lengths: For algorithms that involve encryption, using keys that are too short or lack sufficient entropy can lead to cryptographic breaks. [45]
- Token Limit Exploitation (e.g., CSS-based exfiltration): In scenarios where tokens are excessively large and passed in contexts like CSS selectors, sophisticated techniques might be employed to exfiltrate them in smaller pieces. [75]
Detection and Prevention
Securing JWT implementations requires a multi-layered approach, focusing on robust validation, secure key management, and secure transmission/storage.
1. Rigorous Signature Verification
- Always use
verify()(or equivalent) overdecode(): Ensure your JWT library's verification function is used to check the signature before trusting the payload. [1][8][9][10] - Never trust the
algheader: Explicitly pin the expected algorithm server-side. Do not rely on the algorithm specified in the JWT header to determine the verification method. Whitelist only the necessary algorithms. [20][22][23][76][37][25][13][4][30][9][33][10] - Reject "none" algorithm: Always disallow the "none" algorithm for signature verification in production environments. [36][1][17][12][27][13][14][9][15][10][16]
- Validate unknown algorithms: Reject tokens with unrecognized algorithm values in the header. [35][25][13]
- Validate key type against algorithm: Ensure the cryptographic key type matches the expected algorithm (e.g., don't use an RSA public key as an HMAC secret). [21][23][34][28][4][30][31][9][33]
- Reject tokens with empty/missing signatures: Treat tokens lacking a valid signature segment as invalid. [35][17][18][15][10]
2. Secure Key Management
- Use Cryptographically Strong Secrets/Keys: Generate keys using secure random number generators. For symmetric keys (HS), ensure they are sufficiently long (e.g., 256 bits / 32 bytes minimum) and complex. For asymmetric keys (RS, ES, PS), use appropriate key sizes (e.g., 2048 bits for RSA). [45][17][37][27][77][40][67]
- Secure Secret Storage: Store secrets and private keys securely, ideally using dedicated secrets management systems (e.g., HashiCorp Vault, AWS Secrets Manager). Avoid hardcoding or storing them in version control. [3][2][37]
- Implement Key Rotation: Regularly rotate signing keys and secrets. This limits the impact of a compromised key. Use key versioning to manage transitions smoothly. [44][37][5][49][67]
- Centralized Key Management: For asymmetric keys, use a centralized system for key distribution and management, such as JWKS endpoints. [37][67]
3. Comprehensive Claim Validation
- Validate all Registered Claims: Always verify
exp,nbf,iss, andaud. [36][58][44][37][60][5][13][61][66][67][62][9][64] - Strict Issuer (
iss) Validation: Ensure the issuer is precisely matched against a trusted list. Avoid partial matches. [36][59][60][13][61][62] - Strict Audience (
aud) Validation: Verify that the token is intended for the correct recipient (your service/API). Use an allowlist for audience values. [36][58][60][5][13][63][61][62][64] - Validate Token Lifetime: Set short expiration times (e.g., 15-60 minutes for access tokens) and enforce them strictly. Use refresh tokens for session continuity. [69][44][37][5][61][67]
- Unique Token Identifiers (
jti): Include a unique identifier for each token to enable revocation and prevent replay attacks. [44][37][5][62] - Never Store Sensitive Data in Payload: Exclude PII, credentials, or any confidential information from JWT payloads. Use opaque tokens or other mechanisms for sensitive data. [2][60][5][65][66][67][68][16]
4. Secure Transmission and Storage
- Use HTTPS Exclusively: Always transmit JWTs over TLS/SSL to prevent interception. [36][5][61][16]
- Prefer HttpOnly and Secure Cookies: When using cookies for JWT storage, set the
HttpOnlyflag to prevent JavaScript access and theSecureflag to ensure transmission only over HTTPS. ImplementSameSite=Strictfor CSRF protection. [70][36][5][61][16] - Avoid
localStorage/sessionStoragefor sensitive tokens: These are vulnerable to XSS attacks. If JWTs must be accessed by JavaScript, carefully consider XSS mitigation strategies and accept the associated risks. [70][36][5][71][16] - Avoid JWTs in URL Parameters: Never pass JWTs as URL parameters, as they can be logged by proxies, browsers, and CDNs, or leaked via referrer headers. Use the
Authorization: Bearerheader or secure POST request bodies. [5]
5. Input Validation for Header Parameters
- Sanitize
kidparameter: Never use thekidvalue directly for file path lookups or database queries. Use an allowlist of known key identifiers or a secure mapping mechanism. [7][47][48][49][50][51][52][55][32] - Validate
jku/x5uparameters: Strictly validate these URLs against an allowlist of trusted JWKS endpoints. Disable HTTP redirects. Consider ignoring these parameters entirely and configuring JWKS endpoints server-side. [46][29][53][30][54][55][32][33] - Reject embedded
jwk: Avoid trusting public keys embedded directly in the JWT header. [54][55][56]
Tooling for JWT Security Analysis
A robust set of tools is essential for identifying and exploiting JWT vulnerabilities. Many of these tools automate common attack patterns and provide insights into token structures.
jwt.io: An essential online decoder and debugger for inspecting JWTs. While convenient, avoid pasting sensitive tokens into public online tools. [7][11][38][39][78][18][15]jwt_tool(Python): A comprehensive command-line toolkit for validating, forging, scanning, and tampering with JWTs. It supports numerous exploits, includingalg:none, key confusion,kidinjection, and secret cracking. [76][38][52][79][32]jwt-hack(Rust): A high-performance toolkit for testing, analyzing, and attacking JWTs, including DEFLATE compression support and MCP server integration. [76]- Burp Suite Extensions (JWT Editor, JWT Scanner, JOSEPH): These extensions integrate directly into Burp Suite, providing powerful capabilities for intercepting, decoding, editing, signing, verifying, and attacking JWTs within proxy traffic. They automate many common exploit scenarios. [80][81][82][56]
hashcat: A powerful password cracking tool that can be used to brute-force weak HMAC secrets for HS* algorithms when provided with the JWT and a wordlist. [7][40][15][41][42][32][10]c-jwt-cracker(C): A multi-threaded JWT brute-force cracker for finding HMAC secrets. [41]jwtauditor(Client-side JavaScript): A 100% client-side platform for advanced JWT security analysis, vulnerability detection, and exploitation. [83]jwtXploiter(Python): A tool designed for security testing of JWTs, automating various known CVEs and attack vectors. [55]CookieMonster(Go): While not JWT-specific, this tool can detect and unsign various stateless authentication tokens, including JWTs, often revealing weak keys. [43]
Recent Developments and Emerging Threats
The JWT security landscape is constantly evolving, with new vulnerabilities and attack techniques being discovered. Staying abreast of these developments is crucial for effective defense.
- CVEs in popular libraries: The ecosystem is still seeing critical vulnerabilities disclosed in widely-used JWT libraries (e.g., PyJWT, jsonwebtoken, Hono, pac4j, python-jose), often related to algorithm confusion, improper validation, or handling of specific header parameters. [20][84][21][22][72][35][85][59][34][86][73][13][28][87][31][88]
- RFC 8725bis and updated best practices: The IETF continues to refine best practices for JWT security, addressing newly discovered threats and providing more actionable guidance. [58][62]
- Focus on JWE vulnerabilities: With the increasing use of encrypted JWTs (JWE), vulnerabilities in their processing and decryption are becoming more prominent. [72][73][74]
- Supply chain attacks: The reliance on open-source JWT libraries makes them targets for supply chain attacks. Compromising a library can have a widespread impact. [87]
- AI-assisted vulnerability discovery: LLMs are starting to be used in security code reviews, potentially accelerating the discovery of subtle JWT vulnerabilities. [35]
Where to Go Deeper
For continued learning and hands-on practice, the following resources are invaluable:
- OWASP JWT Cheat Sheet: A comprehensive guide to JWT security best practices and common vulnerabilities. [9][16]
- PortSwigger Web Security Academy: Offers excellent labs and detailed explanations for various JWT attacks, including algorithm confusion and signature bypasses. [40][82][33][10]
jwt_tooldocumentation and wiki: Provides detailed information on its features, attack methodology, and usage. [79][32]- IETF RFC 8725 (JWT Best Current Practices): The foundational document for understanding secure JWT implementation. [58][62]
jwt.io: Useful for decoding and understanding JWT structures, but exercise caution with sensitive tokens. [7][38][39][78][18][15]- Online JWT Pentesting Guides and Writeups: Numerous blogs and repositories offer practical walkthroughs and attack methodologies. ([6][57][69][19][7][3][89][36][2][20][84][21][22][72][35][58][45][23][1][90][44][85][59][34][86][91][92][93][94][95][96][46][76][11][97][17][37][60][5][47][24][98][12][25][26][65][27][48][73][13][28][87][4][99][100][74][63][29][49][50][101][102][38][103][77][104][61][8][78][40][53][14][18][66][30][31][67][88][9][54][51][52][15][55][41][42][79][32][80][81][82][56][33][10][83][105][106][107][64][108][109][110][43][16][111][71])