JWT
suggest changeA JSON Web Token (JWT, RFC 7519) is a compact, URL-safe string that carries a set of claims (a JSON object) together with a cryptographic signature. A server issues a token after a user logs in, the client sends it back with every request (usually in an Authorization: Bearer ... header), and any service that has the right key can check that the token is genuine and unmodified without looking anything up in a database.
This article covers:
- the structure of a token, and building one with only the standard library
- creating and verifying tokens with PyJWT
- registered claims:
exp,nbf,iat,iss,aud,sub,jti - error handling
- asymmetric algorithms: RS256, ES256, EdDSA
- key rotation with
kid, JWK Sets andPyJWKClient - security pitfalls
- a complete access token / refresh token example
Install PyJWT with the optional cryptography dependency, which is needed for the RSA, EC and EdDSA algorithms:
pip install "pyjwt[crypto]"
The examples were run with PyJWT 2.15 and Python 3.13.
Structure of a token
A JWT has three parts separated by dots:
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiI0MiIsIm5hbWUiOiJBbGljZSIsImlhdCI6MTc2MDAwMDAwMH0.7YrXdc1THmctgVq-QfZdD7-TYeSKDF4RkACJ4uZCc10
└──────────── header ──────────────┘ └──────────────────────── payload ─────────────────────────┘ └────────────── signature ────────────────┘
- the header is JSON that names the signing algorithm (
alg) and the token type (typ) - the payload is JSON with the claims
- the signature is computed over
base64url(header) + "." + base64url(payload)
Each part is encoded with base64url (the URL-safe base64 alphabet with = padding removed).
The header and payload are encoded, not encrypted. Anyone who holds a token can read it. The signature only proves who created the token and that nobody changed it. Never put passwords, secrets or sensitive personal data in a JWT.
A JWT with only the standard library
Building an HS256 (HMAC with SHA-256) token by hand is a good way to see that there is no magic involved:
import base64, hashlib, hmac, json
def b64url_encode(data: bytes) -> str:
return base64.urlsafe_b64encode(data).rstrip(b"=").decode("ascii")
def b64url_decode(s: str) -> bytes:
return base64.urlsafe_b64decode(s + "=" * (-len(s) % 4))
def make_hs256(payload: dict, secret: bytes) -> str:
header = {"alg": "HS256", "typ": "JWT"}
h = b64url_encode(json.dumps(header, separators=(",", ":")).encode())
p = b64url_encode(json.dumps(payload, separators=(",", ":")).encode())
signing_input = f"{h}.{p}".encode("ascii")
sig = hmac.new(secret, signing_input, hashlib.sha256).digest()
return f"{h}.{p}.{b64url_encode(sig)}"
def verify_hs256(token: str, secret: bytes) -> dict:
h, p, s = token.split(".")
expected = hmac.new(secret, f"{h}.{p}".encode("ascii"), hashlib.sha256).digest()
if not hmac.compare_digest(expected, b64url_decode(s)):
raise ValueError("bad signature")
return json.loads(b64url_decode(p))
secret = b"a-very-long-random-secret-of-at-least-32-bytes!!"
token = make_hs256({"sub": "42", "name": "Alice", "iat": 1760000000}, secret)
print(token)
print(verify_hs256(token, secret))
tampered = token.split(".")
tampered[1] = b64url_encode(b'{"sub":"1","name":"Mallory","iat":1760000000}')
try:
verify_hs256(".".join(tampered), secret)
except ValueError as e:
print("rejected:", e)
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiI0MiIsIm5hbWUiOiJBbGljZSIsImlhdCI6MTc2MDAwMDAwMH0.7YrXdc1THmctgVq-QfZdD7-TYeSKDF4RkACJ4uZCc10
{'sub': '42', 'name': 'Alice', 'iat': 1760000000}
rejected: bad signature
Changing the payload without knowing the secret produces a signature mismatch. Note hmac.compare_digest, which compares in constant time so an attacker can't learn the correct signature byte by byte from response timings.
This is useful for understanding, but use a library in real code. Correct verification also means checking the algorithm, expiry, audience, issuer and more, and libraries get those details right.
Encoding and decoding with PyJWT
jwt.encode() takes the payload, the key and the algorithm. jwt.decode() verifies the signature and returns the payload:
import jwt
secret = "a-very-long-random-secret-of-at-least-32-bytes!!"
token = jwt.encode({"sub": "42", "name": "Alice", "iat": 1760000000}, secret, algorithm="HS256")
print(type(token).__name__, token)
print(jwt.decode(token, secret, algorithms=["HS256"]))
str eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiI0MiIsIm5hbWUiOiJBbGljZSIsImlhdCI6MTc2MDAwMDAwMH0.7YrXdc1THmctgVq-QfZdD7-TYeSKDF4RkACJ4uZCc10
{'sub': '42', 'name': 'Alice', 'iat': 1760000000}
The token is byte-for-byte identical to the hand-made one. Since PyJWT 2.0, encode() returns str (1.x returned bytes).
The algorithms argument of decode() is a list of algorithms you accept. It's required, and it must not be derived from the token itself (see the security pitfalls section below).
To read a token without verifying it, for example to look at the header and choose a key, use:
print(jwt.get_unverified_header(token))
print(jwt.decode(token, options={"verify_signature": False}))
{'alg': 'HS256', 'typ': 'JWT'}
{'sub': '42', 'name': 'Alice', 'iat': 1760000000}
Never trust claims read this way for authorization decisions.
jwt.decode_complete() verifies the token like decode() but returns a dict with header, payload and signature, which is handy when you need custom header fields after verification.
Generating a secret
For HMAC algorithms the key should be random and at least as long as the hash output: 32 bytes for HS256, 64 for HS512. Use the secrets module:
python -c "import secrets; print(secrets.token_urlsafe(32))"
G4DpJVLxl6y3szeY3QpoHAM7VRQosZTEsTpMo02kbQk
Store it in an environment variable or a secrets manager, never in source code. PyJWT warns about short keys:
import jwt
jwt.encode({"sub": "1"}, "short", algorithm="HS256")
InsecureKeyLengthWarning: The HMAC key is 5 bytes long, which is below the minimum recommended length of 32 bytes for SHA256. See RFC 7518 Section 3.2.
Registered claims
RFC 7519 defines a set of standard claim names. PyJWT validates the time-based ones automatically and the others when you tell it what to expect.
| Claim | Meaning | Checked by PyJWT |
|---|---|---|
exp |
expiration time | always, if present |
nbf |
not valid before | always, if present |
iat |
issued at | must be a number, if present |
iss |
issuer | when issuer= is passed |
aud |
audience (string or list) | when present, audience= is required |
sub |
subject, usually a user id | type only (must be a string) |
jti |
unique token id | type only |
Times are seconds since the Unix epoch. PyJWT converts datetime values in exp, nbf and iat for you, so you can use timezone-aware datetimes when issuing tokens:
from datetime import datetime, timedelta, timezone
import jwt
SECRET = "a-very-long-random-secret-of-at-least-32-bytes!!"
def issue(user_id: int, ttl: timedelta = timedelta(minutes=15)) -> str:
now = datetime.now(timezone.utc)
payload = {
"sub": str(user_id),
"iss": "https://auth.example.com",
"aud": "https://api.example.com",
"iat": now,
"nbf": now,
"exp": now + ttl,
"role": "admin",
}
return jwt.encode(payload, SECRET, algorithm="HS256")
token = issue(42)
claims = jwt.decode(
token,
SECRET,
algorithms=["HS256"],
audience="https://api.example.com",
issuer="https://auth.example.com",
)
print(claims["sub"], claims["role"])
print(claims["exp"] - claims["iat"])
42 admin
900
sub must be a string. Passing an integer user id makes decode() raise InvalidSubjectError: Subject must be a string, so convert it with str().
Validation errors
All validation failures derive from jwt.InvalidTokenError, with more specific subclasses for each problem:
from datetime import datetime, timedelta, timezone
import jwt
SECRET = "a-very-long-random-secret-of-at-least-32-bytes!!"
now = datetime.now(timezone.utc)
def try_decode(token, **kwargs):
try:
jwt.decode(token, SECRET, algorithms=["HS256"], **kwargs)
print("ok")
except jwt.InvalidTokenError as e:
print(f"{type(e).__name__}: {e}")
expired = jwt.encode({"sub": "1", "exp": now - timedelta(seconds=30)}, SECRET, algorithm="HS256")
try_decode(expired)
try_decode(expired, leeway=timedelta(seconds=60))
future = jwt.encode({"sub": "1", "nbf": now + timedelta(hours=1)}, SECRET, algorithm="HS256")
try_decode(future)
aud = jwt.encode({"sub": "1", "aud": "billing"}, SECRET, algorithm="HS256")
try_decode(aud)
try_decode(aud, audience="reports")
try_decode(aud, audience=["reports", "billing"])
iss = jwt.encode({"sub": "1", "iss": "evil.example"}, SECRET, algorithm="HS256")
try_decode(iss, issuer="auth.example.com")
no_exp = jwt.encode({"sub": "1"}, SECRET, algorithm="HS256")
try_decode(no_exp)
try_decode(no_exp, options={"require": ["exp", "sub"]})
try_decode(no_exp + "x")
try_decode("not-a-token")
ExpiredSignatureError: Signature has expired
ok
ImmatureSignatureError: The token is not yet valid (nbf)
InvalidAudienceError: Invalid audience
InvalidAudienceError: Audience doesn't match
ok
InvalidIssuerError: Invalid issuer
ok
MissingRequiredClaimError: Token is missing the "exp" claim
InvalidSignatureError: Signature verification failed
DecodeError: Not enough segments
Things to notice:
leewayallows for clock skew between servers. A few seconds to a minute is typical.- A token with an
audclaim is rejected if you don't passaudience=. If you pass a list, the token's audience must match at least one entry. - A token without
expis accepted, because the claim is optional. Useoptions={"require": [...]}to insist on the claims your application relies on. Tokens that never expire are a liability.
In a web application you usually catch ExpiredSignatureError separately (so the client knows to refresh) and treat every other InvalidTokenError as "401 Unauthorized".
Asymmetric algorithms: RS256, ES256, EdDSA
With HS256 the same secret both creates and verifies tokens, so every service that verifies tokens can also forge them. With asymmetric algorithms the auth server signs with a private key and other services verify with the public key, which can be shared freely.
| Algorithm | Key type | Notes |
|---|---|---|
HS256 / HS384 / HS512 |
shared secret | simple, one service or a trusted group |
RS256 / PS256 |
RSA, 2048+ bits | most widely supported, large signatures |
ES256 |
EC P-256 | small, fast signatures |
EdDSA |
Ed25519 | modern, small, hard to misuse |
Generating an RSA key pair with cryptography and using it:
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import rsa
import jwt
private_key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
public_key = private_key.public_key()
private_pem = private_key.private_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PrivateFormat.PKCS8,
encryption_algorithm=serialization.NoEncryption(),
)
public_pem = public_key.public_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PublicFormat.SubjectPublicKeyInfo,
)
print(public_pem.decode().splitlines()[0])
token = jwt.encode({"sub": "42"}, private_pem, algorithm="RS256")
print(len(token))
print(jwt.decode(token, public_pem, algorithms=["RS256"]))
print(jwt.decode(token, public_key, algorithms=["RS256"]))
-----BEGIN PUBLIC KEY-----
396
{'sub': '42'}
{'sub': '42'}
PyJWT accepts keys either as PEM data (str or bytes) or as cryptography key objects. In production you would load the PEM from a file or a secrets store; the OpenSSL command line works too:
openssl genpkey -algorithm RSA -pkeyopt rsa_keygen_bits:2048 -out private.pem
openssl pkey -in private.pem -pubout -out public.pem
Elliptic curve and Ed25519 keys produce much shorter tokens:
from cryptography.hazmat.primitives.asymmetric import ec, ed25519
import jwt
ec_key = ec.generate_private_key(ec.SECP256R1())
t1 = jwt.encode({"sub": "42"}, ec_key, algorithm="ES256")
print("ES256", len(t1), jwt.decode(t1, ec_key.public_key(), algorithms=["ES256"]))
ed_key = ed25519.Ed25519PrivateKey.generate()
t2 = jwt.encode({"sub": "42"}, ed_key, algorithm="EdDSA")
print("EdDSA", len(t2), jwt.decode(t2, ed_key.public_key(), algorithms=["EdDSA"]))
ES256 140 {'sub': '42'}
EdDSA 140 {'sub': '42'}
Key rotation with kid and JWK Sets
Keys should be replaced from time to time. To verify tokens signed with the old key while new tokens use the new one, put a key id (kid) in the header and publish all valid public keys as a JWK Set (RFC 7517), a JSON document with a keys array:
import json
from cryptography.hazmat.primitives.asymmetric import ec
import jwt
from jwt.algorithms import ECAlgorithm
# the auth server has two signing keys: an old one and the current one
keys = {
"2026-09": ec.generate_private_key(ec.SECP256R1()),
"2026-10": ec.generate_private_key(ec.SECP256R1()),
}
def sign(payload, kid):
return jwt.encode(payload, keys[kid], algorithm="ES256", headers={"kid": kid})
# publish the public halves as a JWK Set
jwks = {"keys": []}
for kid, key in keys.items():
jwk = ECAlgorithm.to_jwk(key.public_key(), as_dict=True)
jwk.update(kid=kid, use="sig", alg="ES256")
jwks["keys"].append(jwk)
print(json.dumps(jwks["keys"][0], indent=2))
# the API server loads the set and picks a key by kid
key_set = jwt.PyJWKSet.from_dict(jwks)
def verify(token):
kid = jwt.get_unverified_header(token).get("kid")
try:
signing_key = key_set[kid]
except KeyError:
raise jwt.InvalidTokenError(f"unknown kid {kid!r}")
return jwt.decode(token, signing_key, algorithms=["ES256"])
print(verify(sign({"sub": "old"}, "2026-09")))
print(verify(sign({"sub": "new"}, "2026-10")))
bad = jwt.encode({"sub": "x"}, ec.generate_private_key(ec.SECP256R1()),
algorithm="ES256", headers={"kid": "nope"})
try:
verify(bad)
except jwt.InvalidTokenError as e:
print(e)
{
"kty": "EC",
"crv": "P-256",
"x": "n-w-jp3SxwvijlWKkHGkWFKEisD9_6SQD-aGggDfv7o",
"y": "OJWr46x_gcFbAeCPgF9MutdBsLLjlED-mvFYqEjnbKA",
"kid": "2026-09",
"use": "sig",
"alg": "ES256"
}
{'sub': 'old'}
{'sub': 'new'}
unknown kid 'nope'
Reading the unverified header to find kid is fine: it only selects a key from your trusted set, and the signature is still verified with that key.
Fetching keys with PyJWKClient
Identity providers (Auth0, Okta, Keycloak, Google, Microsoft Entra ID, AWS Cognito) publish their JWK Set at a URL, often https://<issuer>/.well-known/jwks.json. jwt.PyJWKClient downloads it, caches it and picks the key matching the token's kid. When it sees an unknown kid it refetches the set once, so key rotation on the provider's side just works.
This example runs a tiny local JWKS server so it can run offline:
import json
import threading
from http.server import BaseHTTPRequestHandler, HTTPServer
from cryptography.hazmat.primitives.asymmetric import rsa
import jwt
from jwt.algorithms import RSAAlgorithm
private_key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
jwk = RSAAlgorithm.to_jwk(private_key.public_key(), as_dict=True)
jwk.update(kid="key-1", use="sig", alg="RS256")
JWKS = json.dumps({"keys": [jwk]}).encode()
class Handler(BaseHTTPRequestHandler):
def do_GET(self):
print(" server: GET", self.path)
self.send_response(200)
self.send_header("Content-Type", "application/json")
self.end_headers()
self.wfile.write(JWKS)
def log_message(self, *args):
pass
server = HTTPServer(("127.0.0.1", 0), Handler)
threading.Thread(target=server.serve_forever, daemon=True).start()
jwks_url = f"http://127.0.0.1:{server.server_port}/.well-known/jwks.json"
token = jwt.encode({"sub": "42", "aud": "api"}, private_key,
algorithm="RS256", headers={"kid": "key-1"})
client = jwt.PyJWKClient(jwks_url, cache_keys=True, lifespan=300)
for _ in range(3):
signing_key = client.get_signing_key_from_jwt(token)
claims = jwt.decode(token, signing_key.key, algorithms=["RS256"], audience="api")
print(claims)
server.shutdown()
server: GET /.well-known/jwks.json
{'sub': '42', 'aud': 'api'}
{'sub': '42', 'aud': 'api'}
{'sub': '42', 'aud': 'api'}
The set is downloaded once and served from cache afterwards (lifespan is in seconds). Create one PyJWKClient per process and reuse it, rather than one per request.
With a real provider, you'd also pass issuer= and audience= (your API's client id or identifier) to jwt.decode().
Security pitfalls
Always pin the algorithms. Early JWT libraries trusted the alg header, which allowed two famous attacks: "alg": "none" (an unsigned token) and "algorithm confusion", where an RS256 public key is used as an HS256 secret. PyJWT requires algorithms= and rejects anything not in the list:
import jwt
SECRET = "a-very-long-random-secret-of-at-least-32-bytes!!"
token = jwt.encode({"sub": "1"}, SECRET, algorithm="HS256")
for kwargs in [{}, {"algorithms": ["RS256"]}]:
try:
jwt.decode(token, SECRET, **kwargs)
except jwt.InvalidTokenError as e:
print(f"{type(e).__name__}: {e}")
unsigned = jwt.encode({"sub": "1", "admin": True}, None, algorithm="none")
print(unsigned)
try:
jwt.decode(unsigned, SECRET, algorithms=["HS256"])
except jwt.InvalidTokenError as e:
print(f"{type(e).__name__}: {e}")
DecodeError: It is required that you pass in a value for the "algorithms" argument when calling decode().
InvalidAlgorithmError: The specified alg value is not allowed
eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0.eyJzdWIiOiIxIiwiYWRtaW4iOnRydWV9.
InvalidAlgorithmError: The specified alg value is not allowed
Don't write algorithms=[jwt.get_unverified_header(token)["alg"]], since that brings the vulnerability right back. Each key should be used with exactly one algorithm.
Other rules:
- Validate
audandisswhen tokens come from a shared identity provider. Otherwise a token issued for another application can be replayed against yours. - Keep access tokens short-lived (minutes). A JWT can't be revoked once issued, unless you keep a denylist, which brings back the database lookup JWTs were meant to avoid.
- Don't store secrets in the payload. It's only base64. If you need confidentiality, use JWE (encrypted tokens, supported by
joserfcorauthlib), or keep the data on the server. - Mind where the token lives in the browser.
localStorageis readable by any script injected through XSS. AnHttpOnly,Secure,SameSitecookie is usually safer, combined with CSRF protection. - Prefer opaque server-side sessions for a simple monolithic web app. JWTs pay off when several services need to verify identity without sharing a session store.
Use PyJWT, joserfc or authlib. The once-popular python-jose has been largely unmaintained for years, so avoid it in new code.
Access and refresh tokens
A common pattern is a short-lived access token sent with every request and a long-lived refresh token used only to get new access tokens. The example below adds a type claim so one can't be used in place of the other, a jti to support revocation, refresh token rotation, and a decorator that protects request handlers. It is framework-agnostic: headers is a plain dict, the way a WSGI or ASGI app would expose the request headers.
import functools
import secrets
from datetime import datetime, timedelta, timezone
import jwt
SECRET = secrets.token_bytes(32)
ISSUER = "auth.example.com"
ACCESS_TTL = timedelta(minutes=15)
REFRESH_TTL = timedelta(days=30)
revoked_jtis: set[str] = set() # use Redis or a database in production
def _make(sub: str, kind: str, ttl: timedelta, **extra) -> str:
now = datetime.now(timezone.utc)
payload = {
"iss": ISSUER, "sub": sub, "type": kind,
"iat": now, "exp": now + ttl,
"jti": secrets.token_hex(8),
**extra,
}
return jwt.encode(payload, SECRET, algorithm="HS256")
def login(user_id: str, roles: list[str]) -> dict:
return {
"access": _make(user_id, "access", ACCESS_TTL, roles=roles),
"refresh": _make(user_id, "refresh", REFRESH_TTL),
}
def _verify(token: str, kind: str) -> dict:
claims = jwt.decode(
token, SECRET, algorithms=["HS256"], issuer=ISSUER,
options={"require": ["exp", "iat", "sub", "jti"]},
)
if claims.get("type") != kind:
raise jwt.InvalidTokenError(f"expected {kind} token")
if claims["jti"] in revoked_jtis:
raise jwt.InvalidTokenError("token revoked")
return claims
def refresh(refresh_token: str) -> dict:
claims = _verify(refresh_token, "refresh")
revoked_jtis.add(claims["jti"]) # one-time use: rotate
return login(claims["sub"], roles=["user"])
class Unauthorized(Exception):
pass
def require_auth(role: str | None = None):
def decorator(handler):
@functools.wraps(handler)
def wrapper(headers: dict, *args, **kwargs):
auth = headers.get("Authorization", "")
scheme, _, token = auth.partition(" ")
if scheme.lower() != "bearer" or not token:
raise Unauthorized("missing bearer token")
try:
claims = _verify(token, "access")
except jwt.InvalidTokenError as e:
raise Unauthorized(str(e)) from e
if role and role not in claims.get("roles", []):
raise Unauthorized(f"needs role {role!r}")
return handler(claims, *args, **kwargs)
return wrapper
return decorator
@require_auth()
def get_profile(user):
return f"profile of user {user['sub']}"
@require_auth(role="admin")
def delete_user(user, victim):
return f"user {user['sub']} deleted {victim}"
tokens = login("42", roles=["user"])
hdr = {"Authorization": f"Bearer {tokens['access']}"}
print(get_profile(hdr))
for call in [
lambda: delete_user(hdr, "7"),
lambda: get_profile({}),
lambda: get_profile({"Authorization": f"Bearer {tokens['refresh']}"}),
]:
try:
call()
except Unauthorized as e:
print("401:", e)
new_tokens = refresh(tokens["refresh"])
print(get_profile({"Authorization": f"Bearer {new_tokens['access']}"}))
try:
refresh(tokens["refresh"])
except jwt.InvalidTokenError as e:
print("refresh failed:", e)
profile of user 42
401: needs role 'admin'
401: missing bearer token
401: expected access token
profile of user 42
refresh failed: token revoked
Each refresh token works once. If a stolen refresh token is used after the real client already used it (or the other way around), the second attempt fails, which is a signal to revoke the user's whole session. A real refresh() would also reload the user's current roles from the database rather than hard-coding them.
See Decorators for more on writing decorators like require_auth.
Summary
| Task | Code |
|---|---|
| Create a token | jwt.encode(payload, key, algorithm="HS256") |
| Verify and read | jwt.decode(token, key, algorithms=["HS256"]) |
| Verify with header | jwt.decode_complete(token, key, algorithms=[...]) |
| Peek at the header | jwt.get_unverified_header(token) |
| Set expiry | "exp": datetime.now(timezone.utc) + timedelta(minutes=15) |
| Allow clock skew | leeway=timedelta(seconds=30) |
| Check audience / issuer | audience="...", issuer="..." |
| Require claims | options={"require": ["exp", "sub"]} |
| Catch any failure | except jwt.InvalidTokenError |
| Detect expiry | except jwt.ExpiredSignatureError |
| Add a key id | jwt.encode(..., headers={"kid": "k1"}) |
| Load a JWK Set | jwt.PyJWKSet.from_dict(jwks) |
| Fetch keys from a provider | jwt.PyJWKClient(url).get_signing_key_from_jwt(token).key |
| Make an HMAC secret | secrets.token_urlsafe(32) |