FDE Times dataFDE jobs open 932▼14 Change in open roles over 7 days, like-for-like: roles from companies we started tracking this week are left outNew in 7 days 62Companies hiring 202Remote-friendly 24%Median US pay $201kTop hirer Databricks 92
中文VI

The newspaper of the Forward Deployed Engineer

Guides

PyJWT’s expiry check lets tokens with no expiry through

Seven test tokens and one short function expose the flaws that a demo against a customer’s identity provider usually hides.

ShareLinkedInFacebookX

In brief

  • verify_exp checks exp only when the claim is present; use require to make every token carry exp.
  • The list of algorithms belongs in the API’s configuration and must never come from the token’s alg field.
  • PyJWKClient reloads the JWKS when it meets an unknown kid, but since 2.14.0 it refuses automatic redirects.
Two states of JWT verification. Without require, both the valid and no_exp tokens get ACCEPT, while the expired one is blocked. With require, only valid gets ACCEPT; expired and no_exp are both blocked.
Without require, expired tokens are still blocked but tokens lacking exp are accepted; a test set with only expired tokens would miss the flaw. Source: PyJWT documentation and the article's test cases.

A JWT with no exp claim will not be stopped by PyJWT’s verify_exp option. The library’s documentation states that the option checks expiry only when exp is present in the payload.

If a demo uses only valid tokens with every claim in place, each request returns 200 and the gap stays hidden. It surfaces when the customer’s security team sends a token with exp deliberately left out.

An FDE who connects an API to a customer’s login system has to answer for every such token. This exercise therefore reverses the usual order: build the bad tokens first, prove they are blocked, and only then connect to the IdP. You need Python, a terminal and a basic knowledge of HTTP. You do not need an account with any IdP yet.

Step 1: Install the right version, with crypto support

RSA and ECDSA need the cryptography library, so the PyJWT documentation recommends putting pyjwt[crypto] in your requirements file. The current version, as checked on December 1, 2026, is 2.15.1.

python3 -m venv .venv
source .venv/bin/activate
echo 'pyjwt[crypto]==2.15.1' > requirements.txt
python -m pip install -r requirements.txt
python -c "import jwt; print(jwt.__version__)"

Check: the last command must print 2.15.1. Do not name any file jwt.py, because Python may import it by mistake.

The version number matters for security. PyJWT 2.9.0 through 2.12.1 have a vulnerability that allows the algorithm list to be bypassed when verifying with a PyJWK key; the fix is in 2.13.0. You will use that kind of key in step 4, so look at the lock file before you read the customer’s code.

Step 2: Fix the rules in one function

Create verify.py. The function takes its key from outside, so you can test it on a laptop with a key you generated and later swap in the customer’s key without touching the rules.

# verify.py
import jwt

ALGORITHMS = ["RS256"]
REQUIRED = ["exp", "iss", "aud"]

def verify(token, key, issuer, audience):
    return jwt.decode(
        token,
        key,
        algorithms=ALGORITHMS,
        issuer=issuer,
        audience=audience,
        options={"require": REQUIRED},
    )

RS256 is an assumption for this exercise; on a real project, confirm the algorithm with the customer’s identity team. The API documentation warns against computing the algorithms parameter from the alg in the token itself. Doing so lets the sender choose the rules by which their own token is judged.

The require line closes the gap described at the start: a token missing any one of the three claims is rejected. issuer and audience must also come from your configuration, because values taken from the payload and compared with the payload will always match.

Step 3: Seven tokens, one of which should pass

Create run_cases.py in the same directory. This is a simplified setup: a self-generated RSA key pair plays the IdP, and the addresses and audience are dummy values.

# run_cases.py
import time
import jwt
from cryptography.hazmat.primitives.asymmetric import rsa
from verify import verify

ISS = "https://idp.example.test/"
AUD = "api://claims-review"

def new_key():
    return rsa.generate_private_key(
        public_exponent=65537, key_size=2048
    )

idp, stranger = new_key(), new_key()
now = int(time.time())
base = {"sub": "user-1", "iss": ISS,
        "aud": AUD, "exp": now + 300}
no_exp = {k: v for k, v in base.items() if k != "exp"}

def sign(claims, key=idp):
    return jwt.encode(claims, key, algorithm="RS256")

cases = {
    "valid": sign(base),
    "no_exp": sign(no_exp),
    "expired": sign({**base, "exp": now - 60}),
    "wrong_aud": sign({**base, "aud": "api://other"}),
    "wrong_iss": sign({**base, "iss": "https://evil.test/"}),
    "wrong_key": sign(base, stranger),
    "alg_none": jwt.encode(base, None, algorithm="none"),
}

for name, token in cases.items():
    try:
        verify(token, idp.public_key(), ISS, AUD)
        print(name, "ACCEPT")
    except jwt.PyJWTError as err:
        print(name, type(err).__name__)

Run python run_cases.py and compare each line:

Case Expected result Line of defense
valid ACCEPT Meets every condition
no_exp MissingRequiredClaimError require
expired ExpiredSignatureError Expiry check
wrong_aud InvalidAudienceError audience
wrong_iss InvalidIssuerError issuer
wrong_key InvalidSignatureError Signature
alg_none InvalidAlgorithmError algorithms

Check: temporarily delete the options line and run the script again. no_exp should change to ACCEPT, while expired is still blocked; a test suite containing only an expired token would miss the flaw. Restore the line before you continue.

Blocking alg_none is also required by the standard: RFC 9068, the JWT profile for OAuth 2.0 access tokens, obliges resource servers to reject any JWT whose alg is none.

Step 4: Replace the test key with the customer’s JWKS

Only now does the network come in. The kid in the header identifies the key that signed the token, and PyJWKClient finds the matching key in the JWKS.

# auth.py — replace the three values with your real configuration
import jwt
from jwt import PyJWKClient
from verify import verify

JWKS_URL = "https://idp.example.test/keys"
ISSUER = "https://idp.example.test/"
AUDIENCE = "api://claims-review"

jwks = PyJWKClient(JWKS_URL, cooldown_duration=30)

def verify_request(token):
    key = jwks.get_signing_key_from_jwt(token)
    return verify(token, key, ISSUER, AUDIENCE)

def authenticate(token):
    try:
        return 200, verify_request(token)
    except jwt.PyJWKClientConnectionError:
        return 503, None  # could not fetch the JWKS
    except jwt.PyJWTError:
        return 401, None  # token not accepted

When a kid is missing from the current key set, the client reloads the JWKS. That lets the API keep up when the IdP rotates keys, which a key hard-coded in configuration cannot do. With Entra ID, Microsoft neither sets nor guarantees a rotation schedule, and keys can change immediately in an emergency.

cooldown_duration is the minimum interval between two reloads forced by an unknown kid; the default is 30 seconds. If someone sends 1,000 tokens with made-up kid values in a minute, each client forces only about two reloads. The limit applies per client: four workers with one client each could produce about eight.

The trade-off is that if the IdP rotates its keys just after such a reload, tokens carrying the new kid will be rejected until the cooldown ends, even though they are valid. Agree that callers will retry with backoff, up to a limit, for a total wait longer than the cooldown.

Create PyJWKClient once, when the application starts. If you create one per request, each client keeps its own state and the cooldown has no effect.

Check: take a token from the customer’s test environment and call authenticate; the result must be 200. Then change AUDIENCE to a wrong string; the same token must return 401. Record the error type and the kid for investigation, but do not write the full token to the log.

If the keys cannot be fetched, do not blame the token

When the JWKS cannot be retrieved, the API has no basis for concluding that a token is bad. Returning 401 at that point makes users log in again for nothing and sends the operations team looking in the wrong place. authenticate therefore returns 503 when the connection fails and 401 when the token fails verification.

The connection-error branch comes before the general one because Python runs the first except clause that matches. Do not rely on memory for this ordering; ask the PyJWT version you installed:

python -c "import jwt; print(issubclass(
jwt.PyJWKClientConnectionError, jwt.PyJWTError))"

If the command prints True, swapping the two branches would turn every 503 into a 401. In either branch the request must not proceed; a broken network is no reason to skip verification.

In a real deployment, count 401s and 503s as two separate metrics. If 503s rise, ask the network team; if 401s rise, review the tokens and the configuration.

Check: change JWKS_URL to https://127.0.0.1:9/keys, a port where no service is listening, then restart the process to clear the cached keys. The token that was just accepted should now return 503. If you see 401, check the order of the two except branches first.

At the customer’s site, the fault often lies outside the code

Code that runs well on a laptop may fail to fetch the JWKS once it is deployed in the customer’s environment. One cause to consider early is a redirect: since 2.14.0, PyJWKClient refuses to follow redirects automatically when fetching the JWKS. Ask for the final URL and configure it directly; do not downgrade to avoid the error.

With Entra ID, a web API may accept only tokens whose aud is one of its own AppId URIs. When you see InvalidAudienceError, the question to ask is which API the client requested the token for. Turning off the aud check to make a demo deadline means accepting tokens meant for other services as well.

Multi-tenant Entra applications that use the common metadata face another trap: the issuer in that metadata is a template containing {tenantid}. You must replace that part with the request’s tenant ID and then match it exactly against iss. Check the tenant ID against your list of registered customers before substituting it.

If the customer uses Okta, ask at the kickoff meeting which authorization server issues the tokens. Access tokens issued by the org authorization server are not meant for your API to verify; your own API needs a custom authorization server. If the customer hands you the wrong kind of token, changing parameters in jwt.decode will not help.

Four things to fix before this code goes to production

The typ header: RFC 9068 requires checking that typ is at+jwt, which the verify function does not yet do. Ask whether the IdP issues tokens under this profile, then add the check.

A new kid during the cooldown: authenticate returns 401 even though the token may be valid. Separate this case so that the client knows to retry.

A broken JWKS: an endpoint that responds with unusable content is a different case from a lost connection and needs its own branch.

Multiple issuers: verify_request serves one fixed issuer, so it cannot yet be used for a multi-tenant application.

Turn the exercise into evidence of skill

If you are applying for a role that involves integrating APIs with customers’ login systems, have the story of this lab ready. Put it in a repo with the seven test cases and a README explaining why each token is blocked. Practice explaining when the API returns 401 and when it returns 503.

On your résumé, write: “Built a JWT verifier for an API; tested missing claims, wrong audience, wrong key and alg none,” and list only the parts you have run yourself.

When you hand over to the customer, include the results table from step 3 and invite the security team to add an eighth case. If it gets through, you still have time to fix it before the API serves real users.

Was this article useful?

Use with your AI assistantAsk Claude ↗Ask ChatGPT ↗
10 sources
Read next on the roadmap · Stage 5: DeploymentYour Customer Revoked the Key. Why Can You Still Read the Data?Opened data keys can outlive the kill switch, so FDEs should time it before agreeing to let customers hold their own encryption keys.