Skip to main content

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

· 5 min read
Jagdish Kumawat
Founder @ Dewiride

With PyJWT, the registered claims are ordinary keys in the payload dictionary you pass to jwt.encode: iss, sub, aud, iat, nbf, exp and jti. For the three times you can pass datetime values, and PyJWT turns them into the whole seconds a JWT stores.

Syntax​

Syntax
payload = {
"iss": "<issuer>",
"sub": "<subject>",
"aud": "<audience>",
"iat": <time>,
"nbf": <time>,
"exp": <time>,
"jti": "<id>",
}
token = jwt.encode(payload, <key>, algorithm="<alg>")
PartWhat it does
"iss", "sub", "jti"Strings: who made the token, who it's about and its own ID.
"aud"Who the token is for: one string, or a list of strings.
<time>A UTC datetime, or a Unix time in seconds as an int.
jwt.encode(...)Signs the payload with the key and returns the token.

The PyJWT documentation on the times: "You can pass the expiration time as a UTC UNIX timestamp (an int) or as a datetime, which will be converted into an int."

The Example​

The example signs a token for a user named ada, issued by https://login.example.org for https://photos.example.org. It sets iat and nbf to now, exp two hours later, and jti to a random UUID. Then it reads the claims back without verifying, to show what PyJWT wrote.

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 iss, sub, aud, iat and nbf set to now, exp two hours later and a uuid4 jti, encodes it with jwt.encode and HS256, then prints the token and the claims decoded without verification.

main.py
import base64
import uuid
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=")

now = datetime.now(tz=timezone.utc)
payload = {
"iss": "https://login.example.org",
"sub": "ada",
"aud": "https://photos.example.org",
"iat": now,
"nbf": now,
"exp": now + timedelta(hours=2),
"jti": str(uuid.uuid4()),
}
token = jwt.encode(payload, key, algorithm="HS256")
print(token)
print(jwt.decode(token, options={"verify_signature": False}))

datetime.now(tz=timezone.utc) is the current time in UTC, and timedelta(hours=2) adds two hours. jwt.decode(token, options={"verify_signature": False}) only reads the claims back, without the key.

Step 3: Run It​

Terminal
uv run main.py
Output
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJodHRwczovL2xvZ2luLmV4YW1wbGUub3JnIiwic3ViIjoiYWRhIiwiYXVkIjoiaHR0cHM6Ly9waG90b3MuZXhhbXBsZS5vcmciLCJpYXQiOjE3OTYwNTkzNTMsIm5iZiI6MTc5NjA1OTM1MywiZXhwIjoxNzk2MDY2NTUzLCJqdGkiOiI5MjM0M2Q1Ny00NjQ1LTRmN2EtYjU1NC0wNmI4ODliZWJlMmUifQ.4gZpim6dhcR2lv4FqbfXqKbLQ0IHOIn8YixuFFH2QXg
{'iss': 'https://login.example.org', 'sub': 'ada', 'aud': 'https://photos.example.org', 'iat': 1796059353, 'nbf': 1796059353, 'exp': 1796066553, 'jti': '92343d57-4645-4f7a-b554-06b889bebe2e'}

A zsh terminal where uv run main.py prints the token, then a dictionary with iss, sub ada, aud, iat and nbf the same number, exp 7200 higher and a jti UUID.

What Happened​

  • The datetime values became numbers. iat, nbf and exp are Unix times in seconds, and exp is exactly 7200 higher than iat.
  • The other claims kept their values, in the order of the dictionary.
  • aud is a string, because a string went in. A list would have become a JSON array.

Common Mistakes​

MistakeWhat happensDo this instead
Using datetime.now() without a time zoneThe time is your computer's local time, read as UTC, so it can be hours offUse datetime.now(tz=timezone.utc)
Putting a uuid.UUID object in jtiTypeError: Object of type UUID is not JSON serializableUse str(uuid.uuid4())
Leaving out expPyJWT accepts the token forever unless the verifier requires expAlways set an expiry

Troubleshooting​

SymptomLikely causeFix
TypeError: Issuer (iss) must be a string.iss held something other than a stringPass the issuer as text
Decoding the token later fails with Invalid audienceThe token has an aud, and jwt.decode was called without audiencePass the audience you expect to jwt.decode

FAQ​

Do I have to set all seven claims?​

No. The JWT standard makes every registered claim optional. Set the ones your API checks, and always an expiry.

Can aud hold several audiences?​

Yes. Pass a list, such as ["https://photos.example.org", "https://videos.example.org"], and PyJWT writes a JSON array.

Conclusion​

Registered claims in PyJWT are keys in the payload dictionary, and datetime values for iat, nbf and exp become Unix seconds when you call jwt.encode.

Additional Resources​