AppSec All-in-One – All About JWT and its Attacks

Hello all !!! Here is the first write up in “AppSec All-in-One” series. As like I said I will be taking one attack vector at a time and go deeper into it by explaining each layer in that attack. Now, am going to discuss about “All About JWT and its Attacks“.
 
 
Heads-up: This blog is completely theoretical which helps for easy access and go through the concepts (acts as a revise book for you). A practical walkthrough of all these JWT attacks will be demonstrated in DeDefence YouTube channel. Stay tuned and make sure to subscribe.
 
Why Read This Blog: 
 
Because it covers right from fundamentals, attacks, approaches, mitigation. This blog will be very handy for:
 
  • To prepare for AppSec interviews (Because it is most common topic which is often asked in every interview)
  • Security Professionals
  • Bug Bounty Hunters
  • Developers
  • QA

 

First Things First:

JSON Web Tokens (JWTs) have become a cornerstone of modern web applications and APIs, serving as a standardized, self-contained method for securely transmitting information like user authentication and authorization claims. Unlike traditional session tokens, JWTs store data on the client side, which simplifies architecture in distributed systems. However, this convenience introduces a unique and critical attack surface. The security of any system using JWTs is fundamentally dependent on the cryptographic integrity of the token’s signature.
 
 
This blog synthesizes extensive research on JWT security, revealing that the most severe vulnerabilities stem from improper implementation and flawed signature validation. Attackers can exploit these weaknesses to bypass authentication, escalate privileges, and gain complete control over user accounts.
 
Common attack vectors include:
 
  • Stripping the signature by manipulating the header algorithm to none
  • Cracking weak
  • Guessable secret keys used for signing
  • Tricking servers into using the wrong algorithm (an “algorithm confusion” attack) to validate a forged token

 

Further risks arise from:

  • Injecting malicious parameters into the token header to control the key verification process, potentially leading to path traversal, SQL injection, and the use of attacker-controlled keys.
 
How to mitigate these hinges on a simple principle: Never trust user-controllable input within the token before its signature is rigorously verified.
 
Security best practices mandate the use of strong, high-entropy secret keys, robust cryptographic algorithms, and strict server-side validation that enforces a specific, expected algorithm. By adhering to secure implementation guidelines—including using up-to-date libraries, setting short token expiration times, avoiding sensitive data in the payload, and storing tokens securely—organizations can leverage the power of JWTs without succumbing to their considerable risks.
 

The Anatomy of a JSON Web Token (JWT)

At its core, a JSON Web Token (also known as a “jot”) is a compact, URL-safe standard (RFC 7519) for creating data with an optional signature and encryption. Its payload holds JSON that asserts a number of “claims.” Because it is self-contained, all the information needed to verify the user is inside the token itself, reducing the need for server-side session storage.
 
The Three Parts of a JWT
A JWT is composed of three distinct parts, separated by dots (.), each of which is Base64Url encoded.
 
HEADER.PAYLOAD.SIGNATURE
 
Let’s examine a typical token:
 
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.
eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaXNBZG1pbiI6ZmFsc2V9.
EypViEDiJhjeuXgjtGdibxrFPFZyYKn-KqFeAw3c2No
 
About Header: The header provides metadata about the token, primarily the signing algorithm used and the token type.
  • alg: Specifies the cryptographic algorithm used to sign the token, such as HS256 (HMAC with SHA-256) or RS256 (RSA with SHA-256). This field is the source of several critical vulnerabilities.
  • typ: Declares the token type, which is almost always JWT.
 
About Payload: The payload contains the claims, which are statements about an entity (typically the user) and additional data. The data is structured as a JSON object. Decoded Payload commonly consists of:
  • Registered Claims: Predefined claims like iss (issuer), sub (subject), aud (audience), exp (expiration time), and iat (issued at).
  • Public Claims: Custom claims defined to avoid collisions, usually registered in the IANA JSON Web Token Claims registry.
  • Private Claims: Custom claims created for information sharing between parties.
 
Titbits: The header and payload are only Base64Url encoded, not encrypted. And also keep in mind that the header and payload are Base64Url encoded/decoded not Base64 encoded/decoded. This means anyone who intercepts the token can easily decode and read its contents. Therefore, sensitive information like passwords, credit card numbers, or social security numbers should never be stored in a JWT payload.
 
About Signature: The signature is the cryptographic component that guarantees the token’s integrity. It is created by signing the encoded header and payload with a secret or private key, using the algorithm specified in the header.
 
If an attacker modifies the header or payload, the signature will no longer match when the server re-calculates it, thus invalidating the token—assuming the signature is properly verified.
 
JWS vs. JWE: Signing vs. Encrypting
 
The term JWT is often used interchangeably with JSON Web Signature (JWS), which is the most common implementation.
 
  • JWS (JSON Web Signature): The token is signed to ensure data integrity, but the payload is readable. It proves that the data has not been tampered with.
  • JWE (JSON Web Encryption): The token’s payload is encrypted, providing confidentiality. The content is hidden from parties who do not possess the decryption key.
 
* This blog primarily focuses on JWS, as it is more widely used and is the source of the most common JWT vulnerabilities.
 
Titbits: JWT tokens can be implemented “path-wise” in the same domain. For example: JWT token 1 can be used in domain.com/profile, JWT token 2 can be used in domain.com/cart. So here two JWT tokens have been used for two different paths in single domain. So have a keen observation on implementation of JWT tokens in all the paths of the target domain.
 

The Attacker’s Playbook: Common JWT Vulnerabilities and Exploits

The security of JWTs is brittle; a single implementation flaw can lead to a complete authentication and authorization bypass. The following sections detail the most prevalent attack vectors in JWT. Here you go !!!
 
Attack 01: JWT Token Sent in GET Method
  • Vulnerability: Sending a JWT as a query parameter in a URL (e.g., example.com/api/data?token=eyJ...) instead of in a secure Authorization header. URLs are frequently logged by browsers, proxies, and web servers.

  • Relatable Example: It’s like writing your house key code on the outside of the envelope you mail. Anyone who touches that envelope—the mailman, the sorting facility, or anyone looking over your shoulder—now has your key.

  • Exploitation Steps:

    1. An attacker gains access to the victim’s browser history or a server access log.

    2. They locate the URL containing the full JWT string.

    3. The attacker copies the token and uses it to impersonate the user, gaining full access to their account without needing a password.

  • Mitigation: Always transmit JWTs in the Authorization Header using the Bearer scheme. Ensure the application uses TLS/SSL (HTTPS) to encrypt the data in transit.

 

Attack 02: Improper JWT Token Expiration
  • Vulnerability: The token either lacks an exp (expiration) claim or has a lifespan that is far too long (e.g., several days or weeks). If a token doesn’t expire quickly, a stolen token remains useful to an attacker indefinitely.

  • Relatable Example: This is like a hotel room key card that never deactivates. Even after you check out, if someone finds that card a month later, they can walk right back into the room.

  • Exploitation Steps:

    1. An attacker intercepts a user’s JWT through a Man-in-the-Middle (MitM) attack or Cross-Site Scripting (XSS).

    2. Because the token has no expiration, the attacker can use it to access the system repeatedly over a long period.

    3. Even if the user logs out, the “stolen” token remains valid because the server only checks the signature and the (non-existent) expiry date.

  • Mitigation: Set a short expiration time (e.g., 15 minutes) for access tokens. Use refresh tokens stored in HttpOnly cookies to issue new access tokens safely.

 
Attack 03: Sensitive Information in JWT Payload
  • Vulnerability: Including private data like passwords, Social Security numbers, or internal server roles within the JWT payload. JWTs are encoded, not encrypted; anyone with the token can read the data inside using simple online tools.

  • Relatable Example: It’s like using a clear plastic briefcase to carry your private documents. Everyone can see exactly what is inside, even if the briefcase is “locked” (signed).

  • Exploitation Steps:

    1. An attacker intercepts the JWT or finds it stored in the browser’s localStorage.

    2. They paste the string into a tool like jwt.io.

    3. The attacker reads the “hidden” sensitive data, such as the user’s home address or internal database IDs, which can be used for further social engineering or targeted attacks.

  • Mitigation: Only store non-sensitive identifiers (like a UUID or User ID) in the payload. If you must store sensitive data, use JWE (JSON Web Encryption) to ensure the payload is encrypted and unreadable to third parties.

 
Attack 04: Bypassing Signature Verification with the alg:none Attack
The JWT specification includes an none algorithm, intended for situations where the token’s integrity has already been verified by other means. If a server’s JWT library accepts this algorithm, an attacker can completely bypass signature verification.
 
  • Vulnerability: The server trusts the alg parameter in the header—which is controlled by the attacker—to determine how to validate the token. By setting alg to none, the attacker tells the server that no signature is present and the token should be considered valid as-is.

 

  • Relatable Example: Imagine your office security pass has a field labeled “Verification Method: Biometric Scan.” An attacker scratches that out and writes, “Verification Method: Just Trust Me, Bro.” If the security guard sees this, shrugs, and lets them in without a scan, that’s the none algorithm attack.

 

  • Exploitation Steps:
    1. Capture a legitimate JWT.
    2. Decode the header and change the alg value to none. Attackers often try multiple case variations (NoneNONEnOnE) to bypass naive string filters.
    3. Decode the payload and modify claims, for example, changing "isAdmin": false to "isAdmin": true.
    4. Re-encode the modified header and payload.
    5. Construct the new token by concatenating the parts and adding a trailing dot for the empty signature: [new_header].[new_payload]..
    6. Submit this forged token to the server. If vulnerable, the server will grant elevated privileges.
 
 
Attack 05: Cracking Weak HMAC Secrets (HS256)
When a symmetric algorithm like HS256 is used, the security of the entire token rests on the strength and secrecy of the shared secret key. Developers sometimes use weak, default, or easily guessable secrets, making them vulnerable to offline brute-force attacks.
 
  • Vulnerability: An attacker with a single valid JWT has both the data that was signed and the resulting signature. This is enough to launch a dictionary or brute-force attack to find the secret key.
 
  • Relatable Example: This is like setting your bank account PIN to “1234” or your computer password to “password”. An attacker doesn’t need to be a cryptographic genius; they just need a list of common passwords and a tool that can try them all very quickly.
 
  • Exploitation Steps:
    1. Obtain a valid JWT signed with an HMAC-based algorithm (e.g., HS256).
    2. Use a cracking tool like hashcat (mode 16500) or John the Ripper with a wordlist of common secrets (like rockyou.txt or JWT-specific lists).
    3. The tool repeatedly signs the token’s header and payload with each secret from the wordlist and compares the result to the original signature.
    4. If a match is found, the secret is cracked. The attacker can now forge any token and sign it with the recovered secret.
 
Attack 06: Algorithm Confusion Attacks (RSA to HMAC)
This is a clever and devastating attack that abuses implementation flaws where a server is configured for an asymmetric algorithm (like RS256) but can be tricked into verifying with a symmetric one (HS256).
 
  • Vulnerability: An asymmetric RS256 token is signed with a private key and verified with a public key. A symmetric HS256 token is signed and verified with the same secret key. If an attacker can change the alg header from RS256 to HS256, a poorly implemented server might fetch the public key (which is not secret) and use it as the HS256 secret for verification.
 
  • Relatable Example: Imagine a high-security vault door requires a unique, secret physical key to lock (the private key), but its design can be verified with a publicly available blueprint (the public key). An attacker walks up, slaps a new label on the door that says “Standard Padlock,” and then uses the public blueprint to fashion a flimsy key. If the confused security system uses the blueprint to check the “padlock,” it will accept the forged key and open the door.
 
  • Exploitation Steps:
    1. Obtain the server’s public RSA key. This can often be found at a .well-known/jwks.json endpoint, in mobile app assets, or extracted from a TLS certificate.
    2. Take a valid JWT and decode its header and payload.
    3. Change the alg parameter in the header from RS256 to HS256.
    4. Modify the payload to escalate privileges (e.g., sub: "administrator").
    5. Sign the newly crafted token using the HS256 algorithm, providing the server’s public RSA key as the secret.
    6. Submit the forged token. The server, expecting HS256, will use its own public key to successfully verify the signature.
 
Attack 07: Header Parameter Injection Attacks
The JWT header can contain several optional parameters that dictate how the signature should be verified. If a server blindly trusts these parameters, an attacker can inject values to control the verification process.
 
  1. kid (Key ID) Injection:The kid parameter tells the server which key to use for verification, which is useful when multiple keys are in rotation. Attackers can abuse this if the server uses the kid value in an unsafe way.
    • Path Traversal: If the kid specifies a file path to the key (e.g., /var/www/keys/key123.pem), an attacker can inject path traversal sequences. 
      • Example Payload:"kid": "../../../../../dev/null"
      • Exploit: By pointing to /dev/null, the server attempts to use an empty file as the verification key. The attacker can then sign their forged token with an empty string as the secret, resulting in a valid signature.
    • SQL Injection: If the kid is used to query a database for the key, it can be vulnerable to SQL injection.
      • Example Payload:"kid": "' UNION SELECT 'attacker_controlled_key'--"
      • Exploit: The attacker tricks the database into returning a key they know, which they then use to sign their forged token.
    • Command Injection: If the kid value is passed into a system command, an attacker can inject malicious commands.
      • Example Payload:"kid": "key.pem; whoami"

 

      2. jku (JWK Set URL) and x5u (X.509 URL) Injection: These parameters point to a URL where the server can fetch the key or certificate needed for verification.

  • Vulnerability: If the server does not whitelist trusted domains, an attacker can host their own JSON Web Key (JWK) set or certificate at a URL they control and point the jku or x5u header to it.
 
  • Relatable Example: This is like asking a bouncer to check a guest list, but the guest provides a URL to a list they wrote themselves. If the bouncer doesn’t check who owns the website, they’ll accept the fake list.
 
  • Exploit: The attacker generates their own public/private key pair, hosts the public key at their URL, modifies a JWT payload, and signs it with their private key. The server will fetch the attacker’s public key from the malicious URL and use it to successfully validate the forged token. This can also lead to Server-Side Request Forgery (SSRF) vulnerabilities.

 

     3. jwk (JSON Web Key) Injection (CVE-2018-0114): This parameter allows a public key to be embedded directly into the token’s header.
 
  • Vulnerability: A vulnerable server will trust and use the embedded public key for verification without checking if it’s a known or trusted key.
 
  • Exploit: An attacker generates their own key pair, embeds their public key in the jwk header, modifies the payload for privilege escalation, and signs the token with their corresponding private key. The server will validate the signature using the key provided by the attacker themselves.
 

Flawed Implementations: The Hidden Dangers

 
Beyond cryptographic attacks, many vulnerabilities arise from simple logical flaws in how JWTs are managed and stored.
 
  1. Storing Sensitive Data in the Payload:As established, JWT payloads are merely encoded, not encrypted. Storing any sensitive data—personally identifiable information (PII), internal database IDs, detailed permission structures—creates an information disclosure vulnerability. This data can be read by anyone who obtains the token.

 

     2. Insecure Token Storage: Where the token is stored on the client-side matters immensely.
 
  • Local Storage: Storing JWTs in localStorage is common but dangerous. It is accessible via JavaScript, making tokens vulnerable to theft through Cross-Site Scripting (XSS) attacks. A simple XSS payload can read the token from local storage and send it to an attacker’s server, leading to account takeover.

 

  • Cookies: Storing JWTs in HttpOnly cookies is significantly more secure, as it prevents JavaScript from accessing the token, mitigating XSS-based theft. Additional flags like Secure (ensures the cookie is only sent over HTTPS) and SameSite (mitigates CSRF) should also be used.
 
      3. Infinite Tokens: The Peril of Missing Expiration and Revocation:
 
  • No Expiration (exp claim): A token without an exp claim is valid forever. If stolen, it provides permanent access until the signing key is changed.
 
  • No Revocation Mechanism: JWTs are stateless, meaning the server doesn’t track issued tokens. This makes revocation difficult. If a user logs out or changes their password, their old tokens remain valid until they expire. A robust system requires a server-side revocation list (a blacklist), which reintroduces a stateful component but is often necessary for security.
      4. Leaky Tokens: Passing JWTs in URLs. Transmitting JWTs as URL parameters is highly insecure. This exposes the token in:
    • Browser history.
    • Web server logs.
    • Proxy server logs.
    • The Referer header when clicking links to external sites.
    • This significantly increases the risk of accidental leakage and theft. JWTs should be transmitted in the Authorization header (e.g., Authorization: Bearer <token>) or in secure cookies.
 
Tools of the Trade: The Pentester’s JWT Toolkit:
Several tools are essential for analyzing, manipulating, and attacking JWTs during a penetration test.
 
Tool
Primary Use
Description
Manual Decoding & Forging
A web-based debugger for quickly decoding, verifying, and generating JWTs. Excellent for manual inspection.
Burp Suite Extensions
Integrated Proxy Testing
Includes extensions like JWT Editor (or JOSEPH) and JSON Web Token Attacker for seamless manipulation and attack automation within Burp Suite.
All-in-One CLI Toolkit
A powerful Python script for checking validity, testing known exploits (like alg:none), cracking weak keys, and forging tokens.
Offline Secret Cracking
High-speed tools for brute-forcing HS256 secrets using wordlists and rule-based attacks.
Privacy-First Web Tool
A browser-based tool that performs all analysis locally, preventing token leakage to third-party servers. It checks for over 15 vulnerability types.
Data Manipulation
A versatile web-based tool for encoding/decoding, signing, and manipulating JWTs as part of a larger data processing workflow.
 
JWT Security Best Practices and Mitigation:
 
Securing JWT implementations requires a multi-layered defense focused on strong cryptography, strict validation, and secure handling.
 
  1. Use Strong Algorithms: Prioritize asymmetric algorithms like RS256 or ES256 over symmetric ones. Asymmetric keys prevent attackers from forging tokens even if they obtain the public key.

     2. Use Strong Secrets/Keys:

    • For HMAC (HS256), the secret key must be long, random, and have high entropy (at least 32 bytes). Never use common words, defaults, or hardcoded values.
    • For RSA, use keys of at least 2048 bits.

     3. Rotate Keys Periodically: Implement a key rotation policy to limit the window of exposure if a key is compromised.

     4. Always Verify the Signature: This is the most critical step. Every token must be verified before its payload is trusted or used.

     5. Enforce a Specific Algorithm: Do not trust the alg parameter from the header. Your server should be hardcoded to accept only one specific algorithm (e.g., RS256) and reject any token that specifies a different one. This is the primary defense against algorithm confusion attacks.
 
     6. Validate All Claims: Always check standard claims:
    • exp: Ensure the token has not expired.
    • nbf (Not Before): Ensure the token is not being used prematurely.
    • iss: Verify that the token was issued by the expected authority.
    • aud: Verify that the token is intended for your application.
     7. Sanitize Header Parameters: Never blindly use values from kidjku, or jwk. Use a whitelist of known, trusted key IDs and URLs.
 
     8. Keep Libraries Updated: Use well-maintained, up-to-date JWT libraries to protect against patched vulnerabilities like the none algorithm or Psychic Signatures (CVE-2022-21449).
 
     9. Do Not Store Sensitive Data in the Payload: Use the payload for non-sensitive identifiers and claims only. If confidentiality is required, use JWE.
 
    10. Use Short Expiration Times: Set a short lifetime for access tokens (e.g., 5-15 minutes) and use a refresh token mechanism for longer sessions.
 
    11. Implement a Token Revocation Strategy: For critical applications, maintain a server-side blacklist of revoked tokens to handle logouts and security events immediately.
 
    12. Store Tokens Securely:
    • The best practice is to store JWTs in HttpOnlySecure, and SameSite cookies to protect against XSS and CSRF.
    • Avoid localStorage or sessionStorage due to XSS risks.
 
    13. Transmit Tokens Securely:
    • Always use HTTPS.
    • Pass the token in the Authorization header, not in URL parameters.

 

THATS ALL !!! 🫡

Hope its relatable and helpful. This blog will be the go-to resource for many security enthusiasts, I make sure the content in this blog gets updated whenever there’s new attack / tool / approach came across.

For more don’t miss to follow DeDefence blogs and make sure to subscribe our Youtube Channel. All the best !!! 😎

Table of Contents

Recent Posts

Discover More Information

  • Bug Bounty Take-Aways…

    YouTube: @NahamSec  Playlist: https://www.youtube.com/playlist?list=PLKAaMVNxvLmAkqBkzFaOxqs3L66z2n8LA  ─ This document synthesizes insights from…

  • AppSec All-in-One –…

    Hello all !!! Here is the first write up in…

  • Call Now Button