DEV Community

Dan Lumatic
Dan Lumatic

Posted on Originally published at demo.lumatic-labs.com AI-assisted

How to decode a JWT in Python (and what decoding does not prove)

How to decode a JWT in Python (and what decoding does not prove)

Read any token with the stdlib or PyJWT, then see exactly where decoding stops and verifying starts.

TL;DR

  • The stdlib decode is a split, a padding line, base64.urlsafe_b64decode and json.loads. The padding line is what most snippets omit.
  • To inspect a token, call jwt.decode_complete(token, options={"verify_signature": False}). To act on one, call jwt.decode with the key, algorithms=, audience= and issuer=.
  • A hand-built alg: none token claiming role: admin decodes cleanly, and an HS256 allowlist refuses it with InvalidAlgorithmError.
  • exp is epoch seconds in UTC, so compare it with time.time().

To decode a JWT in Python, you split it on the dots, restore the = padding that base64url dropped, and parse the result as JSON. A few lines of stdlib, no crypto. The same lines decode a forged token that claims role: admin, and nothing in the output says it is fake.

A JWT is three base64url strings joined by dots

A JWT is header.payload.signature: three base64url segments joined by dots, as RFC 7519 defines it. The header names the signing algorithm, the payload holds the claims, and the signature covers the first two parts.

base64url is base64 with - and _ in place of + and /, and JWTs usually drop the trailing = padding. Python's base64.urlsafe_b64decode handles the alphabet but insists on padding. That mismatch causes most of the Incorrect padding errors you will meet.

Try this: replace the LIVE line in tokens.py (set up in the next section) with a token from your own app's Authorization header, with or without the Bearer prefix. Run the script below it and read the iss claim. Check that it names the issuer you expect.

Python needs the padding that base64url dropped

Decoding a JWT payload with the stdlib takes a split, one padding line, a base64url decode and json.loads. Leave out the padding line and the decode fails.

Every script in this post imports three sample tokens (live, expired, forged), built with pinned timestamps and signed with the secret demo-secret-do-not-use-in-production. Save them once as tokens.py next to your scripts. Every output below was copied from a real run on Python 3.12.16 with PyJWT 2.15.1, and yours will match except for the one line where the clock enters (see the exp section).

# tokens.py - the three sample tokens for every script below
LIVE = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJodHRwczovL2FjY291bnRzLmV4YW1wbGUtYXBwLmRldiIsInN1YiI6InVzZXJfODYxMiIsImF1ZCI6ImFwaS5leGFtcGxlLWFwcC5kZXYiLCJyb2xlIjoidmlld2VyIiwiaWF0IjoxNzk1NDI0NDAwLCJleHAiOjE3OTU1MTA4MDAsImp0aSI6IjhmMTRjMmQ5In0.THE1TClLi9-IV3RbicyO4zAJwtFbQEaO233J5a044aY"
EXPIRED = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJodHRwczovL2FjY291bnRzLmV4YW1wbGUtYXBwLmRldiIsInN1YiI6InVzZXJfODYxMiIsImlhdCI6MTc5NTMzODAwMCwiZXhwIjoxNzk1NDI0NDAwfQ.StYU2yZlhiuNOcRKmXvJwMEIzTCV8ymZqh2ahMqqNxk"
FORGED = "eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0.eyJzdWIiOiJ1c2VyXzg2MTIiLCJyb2xlIjoiYWRtaW4ifQ."
Enter fullscreen mode Exit fullscreen mode

The next script shows the padding failure first, then the fix as a copy-paste decode_jwt(token) helper. It strips a Bearer prefix, insists on exactly three parts, and raises a ValueError with a clear message on bad padding or bad JSON.

import base64
import binascii
import json

from tokens import LIVE

header_part, payload_part, signature_part = LIVE.split(".")

# Skip the re-padding and the payload segment fails to decode.
try:
    base64.urlsafe_b64decode(payload_part)
except binascii.Error as exc:
    print("no padding:", exc)


def b64url_json(part):
    part += "=" * (-len(part) % 4)
    try:
        return json.loads(base64.urlsafe_b64decode(part))
    except ValueError as exc:  # bad base64, bad UTF-8 and bad JSON all land here
        raise ValueError(f"bad JWT segment: {exc}") from exc


def decode_jwt(token):
    token = token.strip()
    if token.lower().startswith("bearer "):
        token = token[7:].strip()
    parts = token.split(".")
    if len(parts) != 3:
        raise ValueError(f"expected 3 dot-separated parts, got {len(parts)}")
    header, payload, signature = parts
    return b64url_json(header), b64url_json(payload), signature


header, payload, signature = decode_jwt("Bearer " + LIVE)
print("header: ", header)
print("payload:", payload)
print("signature segment:", signature)

try:
    decode_jwt("not.a-token")
except ValueError as exc:
    print("bad input:", exc)
Enter fullscreen mode Exit fullscreen mode
no padding: Incorrect padding
header:  {'alg': 'HS256', 'typ': 'JWT'}
payload: {'iss': 'https://accounts.example-app.dev', 'sub': 'user_8612', 'aud': 'api.example-app.dev', 'role': 'viewer', 'iat': 1795424400, 'exp': 1795510800, 'jti': '8f14c2d9'}
signature segment: THE1TClLi9-IV3RbicyO4zAJwtFbQEaO233J5a044aY
bad input: expected 3 dot-separated parts, got 2
Enter fullscreen mode Exit fullscreen mode

Add "=" * (-len(part) % 4) before decoding, because the stdlib raises a padding error on a segment that lost its = characters. The expression adds 0 to 3 characters, whatever the segment needs.

The header names the algorithm the sender says signed the token, and sometimes a kid that says which key. The payload holds issuer, subject, audience, a role of viewer, timestamps and a token ID. The last segment is the signature: raw bytes encoded as base64url, so it is gibberish as text and not JSON. The helper returns it as a string and never parses it.

PyJWT reads a token in one call, with no key

PyJWT decodes without verification when you pass options={"verify_signature": False} to decode_complete, which returns the header, payload and signature in one call. It is the scripted version of what the debugger at jwt.io shows when you paste a token.

import jwt  # pip install pyjwt

from tokens import LIVE

decoded = jwt.decode_complete(LIVE, options={"verify_signature": False})

print("header:   ", decoded["header"])
print("payload:  ", decoded["payload"])
print("signature:", decoded["signature"])
Enter fullscreen mode Exit fullscreen mode
header:    {'alg': 'HS256', 'typ': 'JWT'}
payload:   {'iss': 'https://accounts.example-app.dev', 'sub': 'user_8612', 'aud': 'api.example-app.dev', 'role': 'viewer', 'iat': 1795424400, 'exp': 1795510800, 'jti': '8f14c2d9'}
signature: b'Lq5L)K\x8b\xdf\x88Wt[\x89\xcc\x8e\xe30\t\xc2\xd1[@F\x8e\xdb}\xc9\xe5\xad8\xe1\xa6'
Enter fullscreen mode Exit fullscreen mode

decode_complete with verify_signature set to False is the one-call reader: no key, no padding code. You pass neither a key nor algorithms=, because PyJWT asks for those only when it verifies.

Reach for this when you want to look at a token while debugging or logging. Don't let a code path that grants access sit behind it.

A forged token decodes as cleanly as a real one

A JWT decode does not verify the signature, so a forged token decodes with no complaint. Here is the stdlib recipe from above run on a token someone built by hand: header {"alg": "none"}, payload with role: admin, and an empty third segment.

import base64
import json

FORGED = "eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0.eyJzdWIiOiJ1c2VyXzg2MTIiLCJyb2xlIjoiYWRtaW4ifQ."


def b64url_json(part):
    part += "=" * (-len(part) % 4)
    return json.loads(base64.urlsafe_b64decode(part))


header_part, payload_part, signature_part = FORGED.split(".")

print("header: ", b64url_json(header_part))
print("payload:", b64url_json(payload_part))
print("signature segment:", repr(signature_part))
print("payload says admin:", b64url_json(payload_part)["role"] == "admin")
Enter fullscreen mode Exit fullscreen mode
header:  {'alg': 'none', 'typ': 'JWT'}
payload: {'sub': 'user_8612', 'role': 'admin'}
signature segment: ''
payload says admin: True
Enter fullscreen mode Exit fullscreen mode

The forged token names the same subject as the live one, user_8612, and promotes it from viewer to admin. The script prints True for the admin check and no warning of any kind.

The only tells in the decode output are alg: none and an empty signature segment, and you see them only if you print the header and look. Anyone can write a payload, base64url-encode it and send it. Reading a field like role straight from decoded JSON hands that decision to whoever built the token.

Try this: search your codebase for verify_signature, verify=False, get_unverified_ and b64decode near .split("."). Every hit should be logging, debugging or key lookup. If one sits in front of an if that grants access, you have the forged-token hole above. No hits only means those spellings are absent, so read any hand-rolled decoder by eye.

Verifying takes a key and an algorithm allowlist

Verifying a JWT takes the key and a call to jwt.decode with algorithms=, and it raises a specific exception for each way a token can be wrong. The key is the shared secret for HS256, or the issuer's public key for the RS and ES families.

The block below mints a fresh token with jwt.encode, so the exp check stays on and the four outcomes never change with the date.

import time

import jwt

from tokens import FORGED

SECRET = "demo-secret-do-not-use-in-production"
AUD = "api.example-app.dev"
ISS = "https://accounts.example-app.dev"

now = int(time.time())
fresh = jwt.encode(
    {"iss": ISS, "sub": "user_8612", "aud": AUD, "role": "viewer",
     "iat": now, "exp": now + 3600},
    SECRET,
    algorithm="HS256",
)


def check(label, token, key, **kwargs):
    try:
        claims = jwt.decode(token, key, algorithms=["HS256"], **kwargs)
        print(label, "OK:", claims["sub"], claims["role"])
    except jwt.PyJWTError as exc:
        print(label, type(exc).__name__ + ":", exc)


check("right key       ", fresh, SECRET, audience=AUD, issuer=ISS)
check("wrong key       ", fresh, "x" * 32, audience=AUD, issuer=ISS)
check("no audience arg ", fresh, SECRET)
check("forged alg:none ", FORGED, SECRET, audience=AUD, issuer=ISS)
Enter fullscreen mode Exit fullscreen mode
right key        OK: user_8612 viewer
wrong key        InvalidSignatureError: Signature verification failed
no audience arg  InvalidAudienceError: Invalid audience
forged alg:none  InvalidAlgorithmError: The specified alg value is not allowed
Enter fullscreen mode Exit fullscreen mode

Two of the four outcomes need a word. A token with an aud claim and no audience= argument raises InvalidAudienceError: PyJWT insists you say which audience you are, so pass the expected value or disable the check on purpose. The forged token raises InvalidAlgorithmError because alg: none sits outside your ["HS256"] allowlist.

Pass algorithms=, audience= and issuer= on every verify call, and let the exception name tell you which check failed. The allowlist stops a token from choosing its own algorithm, so never fill it from the token's own header. A verifier that trusts the header accepts alg: none as "no signature needed". It can also be fooled by an RS256 token relabeled HS256, which gets checked with the public key used as an HMAC secret.

Read the header unverified only to pick the key

The one production job for unverified decoding is reading the header to choose which key to verify with. A kid header names the key that signed the token, and jwt.get_unverified_header() returns it without touching a signature.

This block also mints its own token, and prints only the kid and the verified claims, so your output matches ours on any day.

import time

import jwt

KEYS = {
    "key-2026-a": "demo-secret-do-not-use-in-production",
    "key-2026-b": "another-demo-secret-at-least-32-bytes-long",
}
AUD = "api.example-app.dev"
ISS = "https://accounts.example-app.dev"

now = int(time.time())
claims = {
    "iss": ISS,
    "sub": "user_8612",
    "aud": AUD,
    "role": "viewer",
    "iat": now,
    "exp": now + 3600,
}
token = jwt.encode(
    claims, KEYS["key-2026-a"], algorithm="HS256", headers={"kid": "key-2026-a"}
)

kid = jwt.get_unverified_header(token).get("kid")
print("kid from unverified header:", kid)

key = KEYS.get(kid)
if key is None:
    print("unknown kid: reject the token")
else:
    try:
        verified = jwt.decode(
            token, key, algorithms=["HS256"], audience=AUD, issuer=ISS
        )
        print("verified:", verified["sub"], verified["role"])
    except jwt.PyJWTError as exc:
        print(type(exc).__name__ + ":", exc)
Enter fullscreen mode Exit fullscreen mode
kid from unverified header: key-2026-a
verified: user_8612 viewer
Enter fullscreen mode Exit fullscreen mode

The kid is only a lookup hint. The key itself comes from your own KEYS dict, an unknown kid gets rejected, and the signature check afterwards decides whether the token is real.

exp is epoch seconds in UTC, so compare epoch to epoch

To read JWT claims in Python and check expiry, treat exp as epoch seconds in UTC and compare it with time.time(). RFC 7519 calls this type NumericDate: seconds since 1970-01-01T00:00:00Z, and a token is expired once the current time reaches exp.

The registered claims you will see most:

  • iss, sub, aud: who issued the token, who it is about, who it is for. aud can be a string or a list, so check which before comparing it yourself.
  • exp, nbf, iat: all NumericDate values. A token is not valid before nbf, and jwt.decode(..., leeway=10) tolerates 10 seconds of clock difference between servers.
  • jti: a unique token ID, which is what a replay check stores and looks up.
import time
from datetime import datetime, timezone

import jwt

from tokens import EXPIRED, LIVE

SECRET = "demo-secret-do-not-use-in-production"

payload = jwt.decode(LIVE, options={"verify_signature": False})
exp = payload["exp"]

print("exp (raw epoch seconds):", exp)
print("exp as UTC datetime:    ", datetime.fromtimestamp(exp, tz=timezone.utc).isoformat())
print("expired:", time.time() >= exp)

old = jwt.decode(EXPIRED, options={"verify_signature": False})
print("expired token, decoded without verifying:", old)

try:
    jwt.decode(EXPIRED, SECRET, algorithms=["HS256"])
except jwt.ExpiredSignatureError as exc:
    print("expired token, verified:", type(exc).__name__ + ":", exc)
Enter fullscreen mode Exit fullscreen mode
exp (raw epoch seconds): 1795510800
exp as UTC datetime:     2026-11-24T09:00:00+00:00
expired: False
expired token, decoded without verifying: {'iss': 'https://accounts.example-app.dev', 'sub': 'user_8612', 'iat': 1795338000, 'exp': 1795424400}
expired token, verified: ExpiredSignatureError: Signature has expired
Enter fullscreen mode Exit fullscreen mode

The live token's exp is 2026-11-24T09:00:00Z. Run the script before that moment and expired prints False. Run it after and it prints True. The expired token's exp, 2026-11-23T09:00:00Z, has already passed, so the verify call raises ExpiredSignatureError whenever you run it. The line above it shows the same token decoding without complaint, because decoding never looks at the clock.

exp is a plain number, so compare it with time.time() and keep local datetimes out of the comparison. datetime.fromtimestamp(exp) without tz= returns local time, and comparing that with a UTC now is the classic off-by-hours bug.

Verify even when the token came from your own server

A token your own server issued is still untrusted input when it comes back, because it has passed through a client, and a client can send you any string it likes. Decode to look at a token while debugging a rejected request or logging what arrived. Verify whenever the answer changes what your code does, such as granting access, choosing a tenant or trusting role.

Your next step: find where your code picks the verification key, and check that it comes from your own table keyed on kid or iss, that an unknown value is rejected, and that every jwt.decode call carries algorithms=, audience= and issuer=.

If you only want to look inside a token without writing a script, a browser-based JWT decoder does the same decoding client-side, with nothing uploaded.

Top comments (0)