LeepCast
Subscribe
All posts
Security

Validating JWTs Safely: Pinned Algorithms, Audience Checks, and the Mistakes Behind Forged Tokens

A JWT that decodes cleanly is not a JWT you should trust. This guide walks through what a server must check before it accepts a token, why algorithm confusion and alg none still work against careless code, and a tested Python validator you can adapt.

LeepCast7 min read

JSON Web Tokens are everywhere: session tokens, API access tokens, OpenID Connect ID tokens, signed webhook payloads. Most of the security trouble with them does not come from broken cryptography. It comes from the receiving side treating a token as trustworthy because it parsed, because its signature matched some key, or because it looked like the right kind of token. This article explains what a JWT verifier actually has to check, why each check exists, and how to wire those checks into code so they cannot be skipped by accident.

What a JWT is, in one paragraph

A signed JWT has three base64url-encoded parts joined by dots: a header, a claims set, and a signature. The header names the signing algorithm in its alg field and may carry a key identifier (kid) and a type (typ). The claims set is a JSON object. RFC 7519 registers a handful of standard claims: iss names the issuer, sub the subject the token is about, aud the intended recipients, exp the moment after which the token must be refused, nbf the moment before which it must be refused, iat when it was issued, and jti a unique identifier useful against replay. Time claims are NumericDate values, meaning seconds since the Unix epoch.

The important consequence is that everything in the header and claims is attacker-controlled until the signature has been verified, and even then it only proves who signed it, not that this particular service should accept it. Verification is a list of independent questions, and a token must pass all of them.

The two classic forgeries: alg none and algorithm confusion

The JWT format includes an algorithm called none, meaning the token carries no signature at all. RFC 8725, the JWT Best Current Practices document, describes attackers simply editing a token header to say none and finding libraries that accept it without checking anything. The fix in principle is easy: libraries should not produce or consume unsigned tokens unless the caller explicitly opts in, and an application should only ever opt in when some other layer already guarantees integrity.

Algorithm confusion is subtler. With HS256 the same secret both signs and verifies, so it must stay private. With RS256 the issuer signs with a private key and anyone can verify with the matching public key, which is usually published, often at a JWKS endpoint. Many libraries expose a single verify function that takes a token and a key and then picks the verification routine based on the alg value inside the token. A developer who only ever expects RS256 passes in the public key. An attacker who changes the header to HS256 and signs the forged token with that same public key, used as an HMAC secret, now produces a signature the server will happily accept. As PortSwigger's write-up notes, the hardest part for the attacker is reproducing the exact byte representation of the key the server holds, such as a PEM string with the same line breaks.

Both attacks share one root cause: the token was allowed to choose how it would be verified. RFC 8725 section 3.1 states the fix directly. A library must let the caller specify which algorithms are acceptable and must refuse anything else, and each key should be tied to exactly one algorithm.

The verification checklist

The following list combines the validation steps in RFC 7519 with the practices in RFC 8725. Treat it as the minimum for any service that accepts JWTs from outside its own process.

  1. Pin the algorithm list on the server. Pass something like algorithms=["RS256"] and never derive it from the token header.
  2. Select the key from your own trusted configuration. If you look keys up by kid, look them up in a key set you fetched from a known issuer URL, and treat the kid string as untrusted input that must not reach a file path, SQL query, or shell.
  3. Verify the signature before reading any claim for a decision. Every cryptographic step must succeed; with nested tokens, both layers must verify.
  4. Check iss against the exact issuer you expect, and confirm the signing key actually belongs to that issuer.
  5. Check aud. If the issuer serves more than one relying party, the token must name your service, and a token without an audience should be refused.
  6. Enforce exp and nbf with a small leeway for clock skew. RFC 7519 suggests a few minutes at most; tens of seconds is usually enough.
  7. Require the claims you depend on. A missing exp is not the same as a token that never expires; it is a malformed token.
  8. Check the token type. If one issuer mints several kinds of JWT, give each kind a distinct typ value or another distinguishing claim, and reject the wrong kind.
  9. Never follow jku or x5u header URLs supplied by the token unless they match an allowlist; otherwise the token is choosing its own trust anchor and can also trigger server-side request forgery.

A tested validator in Python

The example below uses PyJWT 2. x and was run against version 2.15.1. It issues tokens with an HMAC key so it is self-contained, then verifies them with every check from the list that applies to a single-issuer setup. The second half throws four bad tokens at the validator to show that each one fails for the expected reason. Install the library with pip install pyjwt and run the file directly.

python
import secrets
import time

import jwt  # PyJWT 2.x

KEY = secrets.token_bytes(32)  # 256 random bits, never a password
ISSUER = "https://auth.example.com"
AUDIENCE = "orders-api"
TOKEN_TYPE = "access+jwt"


def issue(sub, aud=AUDIENCE, typ=TOKEN_TYPE, ttl=300):
    now = int(time.time())
    claims = {"iss": ISSUER, "sub": sub, "aud": aud, "iat": now, "exp": now + ttl}
    return jwt.encode(claims, KEY, algorithm="HS256", headers={"typ": typ})


def verify_access_token(token):
    decoded = jwt.decode_complete(
        token,
        KEY,
        algorithms=["HS256"],          # pinned by the server, not the token
        audience=AUDIENCE,
        issuer=ISSUER,
        leeway=30,                     # seconds of clock skew
        options={"require": ["exp", "iat", "iss", "sub", "aud"]},
    )
    if decoded["header"].get("typ") != TOKEN_TYPE:
        raise jwt.InvalidTokenError("wrong token type")
    return decoded["payload"]


print("valid ->", verify_access_token(issue("user-42"))["sub"])

attacks = {
    "unsigned (alg none)": jwt.encode(
        {"iss": ISSUER, "sub": "admin", "aud": AUDIENCE,
         "iat": int(time.time()), "exp": int(time.time()) + 300},
        None, algorithm="none"),
    "wrong audience": issue("user-42", aud="billing-api"),
    "wrong type": issue("user-42", typ="JWT"),
    "expired": issue("user-42", ttl=-120),
}

for name, token in attacks.items():
    try:
        verify_access_token(token)
        print(f"{name}: ACCEPTED (bug!)")
    except jwt.InvalidTokenError as exc:
        print(f"{name}: rejected ({type(exc).__name__})")

Running it prints one accepted token and four rejections: the unsigned token fails with InvalidAlgorithmError because none is not in the pinned list, the token for billing-api fails with InvalidAudienceError, the generic JWT-typed token fails the custom type check, and the expired token fails with ExpiredSignatureError even after the 30-second leeway. The custom type value access+jwt is just an application-chosen label; what matters is that some other kind of token from the same issuer, such as an ID token, cannot pass as this one.

Switching to asymmetric keys

In production, an API usually verifies tokens signed by a separate identity provider with RS256, ES256, or EdDSA. PyJWT's PyJWKClient fetches the provider's JWKS document, caches it, and picks the key whose kid matches the token, refreshing once if the kid is unknown. The verification call stays the same shape: you still pass algorithms, audience, issuer, and required claims explicitly. The JWKS URL itself comes from your configuration, never from the token.

Common mistakes, and what they look like in code

  • Decoding without verifying. Reading claims via an unverified decode or get_unverified_header for anything beyond picking a key means trusting attacker input.
  • Letting the header pick the algorithm. Any code path that passes the token's own alg value into the verifier reintroduces algorithm confusion.
  • Using a password as an HMAC secret. RFC 8725 forbids human-memorable passwords as HMAC keys because a captured token can be brute-forced offline. Generate at least 256 random bits instead.
  • Accepting any audience. A token minted for a reporting service should not unlock the payments API just because both trust the same issuer.
  • Ignoring token kinds. If refresh tokens, ID tokens, and access tokens share an issuer and key, without a typ or claim distinction any of them may pass as another.
  • Skipping required-claim checks. Some libraries only validate exp if it is present, so a token without one silently lives forever unless you require it.
  • Disabling checks in tests and shipping the flag. Options such as verify_signature set to False tend to leak into production through shared helper functions.

When a JWT is the wrong tool

A signed JWT is valid until it expires, and a stateless verifier has no way to know that the user logged out, changed a password, or had their account suspended in the meantime. If you need instant revocation, you either keep access tokens very short-lived and back them with a revocable refresh token, or you check a server-side record on each request, at which point an opaque random session ID stored in a database is often simpler and leaks less information. JWT payloads are only encoded, not encrypted, so anything placed in a signed token is readable by whoever holds it. Use a JWT when a stateless, verifiable statement crossing a trust boundary is genuinely what you need, not by default.

A quick review checklist

When reviewing JWT handling in a pull request, ask five questions. Where does the algorithm list come from? Where does the key come from? Are issuer and audience compared to fixed expected values? Which claims are required? Can a different kind of token from the same issuer pass this check? If every answer points to server-side configuration rather than to the token itself, the verifier is in good shape.

Share

Enjoyed this?

Get the next deep dive in your inbox. No spam — just the stories worth reading.

Subscribe to the newsletter

Comments