Skip to main content

How to Add Custom Claims to a JWT in Python with PyJWT

· 7 min read
Jagdish Kumawat
Founder @ Dewiride

PyJWT takes your custom claims as part of the dictionary you pass to jwt.encode: {"name": "Ada", "roles": ["editor"]}. Each key becomes a claim, with any value JSON can hold, and jwt.decode gives them back in a dictionary once it has checked the token.

Syntax​

Syntax
payload = {
"<name>": <value>,
}
token = jwt.encode(payload, <key>, algorithm="<alg>")

claims = jwt.decode(token, <key>, algorithms=["<alg>"])
claims["<name>"]
PartWhat it does
"<name>"The claim's name, a string. Any text works, a URL included.
<value>Any value JSON can hold: a str, an int or a float, True or False, None, a list or a dict.
<key>The signing key, here 32 bytes for HS256.
<alg>The signing algorithm, here HS256.
claimsThe verified claims, as a dictionary: yours and the registered ones.

The PyJWT documentation for jwt.encode describes the payload as "JWT claims, e.g. dict(iss=..., aud=..., sub=...)", and says it raises a TypeError "if payload is not a dict".

The Example​

The example signs a token for a user named Ada with three custom claims of three JSON types: name, a string; roles, a list; and https://photos.example.org/quota, a dictionary with an album limit and a storage limit. The last one has a URL as its name, so that no other service's claim can have the same name. Then the example verifies the token and reads one value back.

Prerequisites​

  • uv and Python. This guide uses uv 0.13.10 with Python 3.15.2.

Step 1: Create the Project​

Terminal
uv init --no-package demo
cd demo
uv add pyjwt

uv init --no-package demo makes a project folder named demo, and uv add pyjwt installs PyJWT, version 2.15.1 here.

Step 2: Write the Code​

Replace the contents of main.py:

main.py, which builds a payload with sub ada, exp one hour from now, name Ada, roles editor and viewer, and a dictionary under https://photos.example.org/quota with albums 10 and storage_gb 50, signs it with jwt.encode and HS256, verifies it with jwt.decode, and prints the token, the claims and the quota's albums.

main.py
import base64
from datetime import datetime, timedelta, timezone

import jwt

# The signing key: 32 random bytes, written as base64.
# It's in the code only for this example; a real app loads it from its configuration.
key = base64.b64decode("C4iNOOORzmu+fnrPK29yq/9n92b/zf5mOs5KvOMaY64=")

payload = {
"sub": "ada",
"exp": datetime.now(tz=timezone.utc) + timedelta(hours=1),
"name": "Ada", # a string
"roles": ["editor", "viewer"], # a list
"https://photos.example.org/quota": {"albums": 10, "storage_gb": 50}, # a dictionary
}
token = jwt.encode(payload, key, algorithm="HS256")
print(token)

claims = jwt.decode(token, key, algorithms=["HS256"])
print(claims)
print(claims["https://photos.example.org/quota"]["albums"])
  • The dictionary payload holds the claims. sub and exp are registered claims, and name, roles and the quota are custom ones. The comments name each one's type.
  • exp is a datetime. PyJWT turns a datetime in exp, iat or nbf into a Unix time, but not in your own claims.
  • jwt.decode(token, key, algorithms=["HS256"]) checks the signature and the expiry, then returns the claims.
  • claims["https://photos.example.org/quota"]["albums"] reads a value inside the dictionary claim.

Step 3: Run It​

Terminal
uv run main.py
Output
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJhZGEiLCJleHAiOjE3OTYyOTE2MzEsIm5hbWUiOiJBZGEiLCJyb2xlcyI6WyJlZGl0b3IiLCJ2aWV3ZXIiXSwiaHR0cHM6Ly9waG90b3MuZXhhbXBsZS5vcmcvcXVvdGEiOnsiYWxidW1zIjoxMCwic3RvcmFnZV9nYiI6NTB9fQ.CPPieTw6e0YVDeuTiWXqS6-eQ1CEiIlrksePw_-jdtY
{'sub': 'ada', 'exp': 1796291631, 'name': 'Ada', 'roles': ['editor', 'viewer'], 'https://photos.example.org/quota': {'albums': 10, 'storage_gb': 50}}
10

A zsh terminal where uv run main.py prints the token, then the claims with sub ada, exp, name Ada, roles editor and viewer, and the quota dictionary with albums 10 and storage_gb 50, then 10.

The command is the same in zsh, bash and PowerShell.

What Happened​

  • The claims came back with the same names and types. roles is a list and the quota a dictionary, not text.
  • exp came back as a number, the Unix time one hour after the token was made.
  • The last line read 10 from inside the dictionary claim, after the token was verified.

Common Mistakes​

MistakeWhat happensDo this instead
A datetime in your own claim, such as "joined"TypeError: Object of type datetime is not JSON serializable. PyJWT converts only exp, iat and nbfConvert it to a Unix time: int(joined.timestamp())
A set as a valueTypeError: Object of type set is not JSON serializableUse a list, such as sorted(roles)
A tuple as a valueIt comes back as a listExpect a list when you read it
A dictionary with numbers as keysThe keys come back as strings: {1: "a"} becomes {'1': 'a'}Use strings as keys
float("nan") or float("inf") as a valuePyJWT writes NaN or Infinity, which isn't JSON, and other services' libraries reject the token. See Fixed: "JWT Claims Set must be a top-level JSON object" in jose for a PyJWT TokenSend None for "no value"
Reading a claim with claims["roles"] when some tokens don't have itKeyError: 'roles'claims.get("roles"), which gives None

Troubleshooting​

SymptomLikely causeFix
TypeError: Expecting a dict object, as JWT only supports JSON objects as payloads.A list, a string or another value that isn't a dictionary was passed to jwt.encodePass a dictionary
TypeError: Object of type … is not JSON serializableA claim holds a value JSON can't holdTurn it into a string, a number, a list or a dictionary first
KeyError when reading a claimThe token doesn't have that claimUse .get(), or require the claim when decoding

FAQ​

Can a custom claim hold a list or a dictionary?​

Yes. A claim's value can be any JSON value, and PyJWT writes it with Python's json module. Lists and dictionaries come back as they were.

Why does one claim have a URL as its name?​

Short names like quota can collide with another service's claim of the same name. The JWT standard, RFC 7519, says a new claim name should either be registered with IANA or be collision-resistant, and it names domain names as one way to make it so. A URL on a domain you control is such a name.

Does PyJWT check my custom claims?​

Only whether they're there, and only when you ask. jwt.decode(token, key, algorithms=["HS256"], options={"require": ["roles"]}) stops a token without roles with jwt.exceptions.MissingRequiredClaimError: Token is missing the "roles" claim. The PyJWT documentation for this require option says it "Only verifies that the claims exists. Does not verify that the claims are valid." Checking that roles is a list is up to your code.

Conclusion​

Put your claims in the dictionary you pass to jwt.encode, and read them from what jwt.decode returns. Keep values to what JSON can hold, give claims that other services may see a URL name, and check each one's type before your code relies on it.

Additional Resources​