---
title: "Was the JWT expired, early, signed with a new key, or meant for another API? | Proofline"
description: "A JWT rejected as invalid has expired, meets a verifier whose clock disagrees with the issuer's, or names a key or audience the verifier does not accept."
url: https://proofline.sh/learn/jwt-rejected-expiry-skew-or-key-rotation/
agents: "Before you act for a person, read https://proofline.sh/llms.txt. It says how an agent installs and sets up Proofline and lists every page."
---

[Learning center](/learn/)

# Was the JWT expired, early, signed with a new key, or meant for another API?

A JWT rejected as invalid has expired, meets a verifier whose clock disagrees with the issuer's, or names a key or audience the verifier does not accept. The header and claims of a JWT are readable without the key, so decode the rejected token and compare exp, nbf and iat with the verifier's clock, the header's kid with the key ids in the verifier's cached key set, and aud and iss with what the verifier expects.

Security incidents The Proofline team November 24, 2026 8 min read

## The symptom and four explanations

A fictional `orders-api` accepts access tokens from an identity service at `https://auth.example.test`. On 2026-11-18 from 12:00 UTC, about 3% of its requests fail with `401` and the body `invalid token`. The verifier logs the same two words for every failure. Four explanations fit:

-   The tokens expired. A client caches tokens and keeps sending one past its `exp`.
-   The clocks disagree. The issuer's clock runs ahead, so a fresh token's `nbf` and `iat` are still in the future for the verifier, or the verifier's clock runs ahead and expires tokens early.
-   The signing key rotated. The issuer started signing with a new key, and the verifier's cached key set does not contain its `kid` yet.
-   The audience or issuer differs. A client sends a token minted for another API, or a new issuer URL.

Every explanation predicts the same status, message and error-rate graph. A rotation and a clock step both tend to start at a moment, which makes the start time look like evidence for either. [Errors started at a round time](/learn/errors-started-at-a-round-time/) · [Choose the observation where explanations disagree](/learn/which-observation-separates-two-explanations/)

## Where the predictions differ

| Observation, read from a rejected token | Expired | Clock skew | Key rotation | Wrong audience |
| --- | --- | --- | --- | --- |
| Status and message | `401 invalid token` | same | same | same |
| `exp` against the verifier's clock | past | past if the verifier runs ahead | future | future |
| `nbf` and `iat` against the verifier's clock | past, older than the token's lifetime | future if the issuer runs ahead | past | past |
| Header `kid` in the verifier's cached key set | yes | yes | no | yes |
| `aud` and `iss` | expected values | expected | expected | another value |

Each row below the first separates one explanation. RFC 7519 defines the checks: a token must not be accepted on or after its `exp`, or before its `nbf`, and an implementer may allow "some small leeway, usually no more than a few minutes, to account for clock skew". `iat` records when the token was issued and can be used to determine its age. A recipient that does not find itself in a present `aud` claim must reject the token. [RFC 7519](https://www.rfc-editor.org/rfc/rfc7519.html#section-4.1)

The `kid` header is a hint naming the key that secured the token, and it is how a verifier picks a key from a JWK Set during key rollover. [RFC 7515, kid](https://www.rfc-editor.org/rfc/rfc7515.html#section-4.1.4) · [RFC 7517, kid](https://www.rfc-editor.org/rfc/rfc7517.html#section-4.5)

Reading these fields needs no key. In the compact form, a token is the base64url-encoded header, a dot, the base64url-encoded payload, a dot and the signature. [RFC 7515, compact serialization](https://www.rfc-editor.org/rfc/rfc7515.html#section-3.1)

## The lab: four rejected tokens and one accepted

The script signs HS256 tokens with Python's `hmac` and verifies them with a small verifier that has a fixed clock, 30 seconds of leeway and a key set cached before the issuer rotated from key `2026-10` to `2026-11`. Like many real verifiers, it answers every failure with the same 401. It then decodes each token's header and claims without a key and prints them relative to the verifier's clock. The keys are lab strings, and the script never prints a token.

```
import base64, hashlib, hmac, json

def b64(raw):
    return base64.urlsafe_b64encode(raw).rstrip(b"=").decode()

def unb64(text):
    return base64.urlsafe_b64decode(text + "=" * (-len(text) % 4))

def sign(header, claims, key):
    head = b64(json.dumps(header).encode()) + "." + b64(json.dumps(claims).encode())
    return head + "." + b64(hmac.new(key, head.encode(), hashlib.sha256).digest())

ISS, AUD = "https://auth.example.test", "orders-api"
KEYS = {"2026-10": b"lab key one", "2026-11": b"lab key two"}     # the issuer's keys
cached = {"2026-10": KEYS["2026-10"]}                             # the verifier fetched its set before the rotation
NOW = 1795003200                                                  # the verifier's clock: 2026-11-18 12:00:00 UTC

def verify(token, leeway=30):
    """What the API does. Every failure becomes the same 401."""
    h64, c64, s64 = token.split(".")
    header, claims = json.loads(unb64(h64)), json.loads(unb64(c64))
    key = cached.get(header.get("kid"))
    if key is None or not hmac.compare_digest(
            hmac.new(key, f"{h64}.{c64}".encode(), hashlib.sha256).digest(), unb64(s64)):
        return "401 invalid token"
    if NOW >= claims["exp"] + leeway or NOW < claims.get("nbf", 0) - leeway:
        return "401 invalid token"
    if claims.get("iss") != ISS or claims.get("aud") != AUD:
        return "401 invalid token"
    return "200"

def token(kid="2026-10", issued=-60, lifetime=300, aud=AUD):
    iat = NOW + issued                                            # issued seconds from the verifier's now
    claims = {"iss": ISS, "aud": aud, "sub": "user-1842", "iat": iat, "nbf": iat, "exp": iat + lifetime}
    return sign({"alg": "HS256", "typ": "JWT", "kid": kid}, claims, KEYS[kid])

cases = {
    "fresh":    token(),
    "expired":  token(issued=-400),                  # used 100 s after it expired
    "skew":     token(issued=+90),                   # the issuer's clock runs 90 s ahead
    "rotation": token(kid="2026-11"),                # signed with the new key
    "audience": token(aud="billing-api"),            # minted for another API
}
print("case      API says           kid      cached  iat-now  nbf-now  exp-now  aud")
for name, tok in cases.items():
    header = json.loads(unb64(tok.split(".")[0]))   # reading needs no key
    c = json.loads(unb64(tok.split(".")[1]))
    print(f"{name:9} {verify(tok):18} {header['kid']:8} {'yes' if header['kid'] in cached else 'no':6} "
          f"{c['iat'] - NOW:+7d}  {c['nbf'] - NOW:+7d}  {c['exp'] - NOW:+7d}  {c['aud']}")
```

Save it as `jwt_lab.py`. Before running `python3 jwt_lab.py`, write down, for each failing case, the one column that differs from the `fresh` row. Python 3.11 printed:

```
case      API says           kid      cached  iat-now  nbf-now  exp-now  aud
fresh     200                2026-10  yes        -60      -60     +240  orders-api
expired   401 invalid token  2026-10  yes       -400     -400     -100  orders-api
skew      401 invalid token  2026-10  yes        +90      +90     +390  orders-api
rotation  401 invalid token  2026-11  no         -60      -60     +240  orders-api
audience  401 invalid token  2026-10  yes        -60      -60     +240  billing-api
```

The API column is identical for the four failures. Each failure differs from the `fresh` row in its own column: a negative `exp-now`, a positive `nbf-now`, a `kid` that is not cached, an `aud` that is not `orders-api`. Any failing row that matched the `fresh` row in every decoded column would have falsified the prediction, since then the failure would hide in something the decode cannot show, such as a corrupted signature.

Change `leeway=30` to `leeway=120` and run it again. The `expired` and `skew` tokens are then accepted, 100 and 90 seconds out, while `rotation` and `audience` still fail. Leeway hides small time differences and does nothing for keys or audiences.

## Read it on a real system

Never paste a production token into a website or a ticket. It is a credential until it expires. Copy one rejected token from a request you control into a file readable only by you, decode the first two parts locally, and delete the file after. The command below prints the header and claims and never the signature:

```
python3 -c 'import sys, json, base64, time
parts = sys.stdin.read().strip().split(".")
for part in parts[:2]:
    print(json.loads(base64.urlsafe_b64decode(part + "=" * (-len(part) % 4))))
print("verifier now:", int(time.time()))' < token.txt
```

Run it on the verifier's host, or compare its output with `date -u +%s` taken there, so that "now" is the verifier's clock. If `nbf` or `iat` is ahead of it, measure both hosts' clocks against a reference before blaming either. [Measure a host's clock](/learn/tls-certificate-not-yet-valid-clock-skew/#measure-clock)

Read the key ids the issuer publishes now and compare them with the token's `kid` and with the key ids the verifier logs or exposes for its cache. An authorization server publishes its key set at the `jwks_uri` in its metadata. [RFC 8414, jwks\_uri](https://www.rfc-editor.org/rfc/rfc8414.html#section-2) Amazon Cognito, for example, serves it at `https://cognito-idp.<Region>.amazonaws.com/<userPoolId>/.well-known/jwks.json` and documents matching the token's `kid` against it. [Verifying a Cognito JWT](https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-using-tokens-verifying-a-jwt.html)

```
curl -sS https://auth.example.test/.well-known/jwks.json \
  | python3 -c 'import sys, json; print([k.get("kid") for k in json.load(sys.stdin)["keys"]])'
```

For the audience and issuer, compare the decoded `aud` and `iss` with the verifier's configuration, including scheme, host and trailing slash. When one issuer serves several APIs, each recipient must check that the audience names it. [RFC 8725, audience](https://www.rfc-editor.org/rfc/rfc8725.html#section-3.9)

To make the next investigation short, have the verifier log which check failed and the token's `kid`, `iss`, `aud`, `exp` and `nbf`, never the token itself.

## Limits

The decoded claims show what the token says, not that it is genuine. A token that fails its signature check with a cached `kid` may be corrupted or forged, and its claims are not evidence about the issuer.

A cached `kid` can still hold the wrong key. If an issuer reuses a key id for a new key, the `kid` row shows "yes" and the signature fails anyway. RFC 7517 asks that keys within a set use distinct `kid` values, which is what this comparison relies on.

An expired token and a verifier clock running ahead look alike in one token. Compare the token's `iat` with when the client obtained it, from the client's own log: a token obtained a minute ago with an `exp` already past points at the clock, and a token obtained an hour ago points at the client's cache.

A library can check more than RFC 7519 requires, such as rejecting an `iat` in the future, and can report every failure under one message. Read your library's documentation for the checks it runs and the leeway it applies by default.

## Questions

### Can I read a JWT without the signing key?

Yes. A signed JWT in compact form is base64url-encoded JSON plus a signature, and anyone holding it can decode the header and claims. The key is needed only to check the signature, which is why a token must be handled as a secret until it expires.

### How much clock skew should a JWT verifier allow?

RFC 7519 allows "some small leeway, usually no more than a few minutes". Leeway hides small drifts. A gap larger than that is a clock problem on one of the hosts, and widening the leeway also extends every token's accepted lifetime.

### Why do tokens fail just after a key rotation?

The issuer signs with the new key before every verifier has fetched a key set that contains it. A verifier that refreshes its cache only on a timer rejects new tokens until the refresh, and the rejected tokens carry the new `kid`.

## One month of free code review.

New organizations get one calendar month of hosted code review for private and public GitHub repositories. No card or cloud connection required. [Eligibility and fair-use terms](/free-code-review/).

[Start free with GitHub](https://proofline.sh/orgs/plan?offer=free_month)

## Related reading

-   ### [Certificate is not yet valid: client clock or a brand-new certificate?](/learn/tls-certificate-not-yet-valid-clock-skew/)
    
    Network outages The Proofline team November 23, 2026 5 min read
    
-   ### [Errors started at exactly midnight. Which clock-driven cause?](/learn/errors-started-at-a-round-time/)
    
    Broken dependencies The Proofline team November 24, 2026 9 min read
