Skip to main content

How to Check a JWT's Issuer and Audience in Python with PyJWT

· 5 min read
Jagdish Kumawat
Founder @ Dewiride

PyJWT's jwt.decode checks a token's issuer and audience when you pass issuer= and audience=. It also does something many people trip over: a token that has an aud is rejected with Invalid audience when you don't pass any audience at all.

Syntax​

Syntax
claims = jwt.decode(
<token>,
<key>,
algorithms=["<alg>"],
issuer="<expected iss>",
audience="<expected aud>",
)
PartWhat it does
<token>, <key>The JWT to verify and the key that checks its signature.
algorithmsThe signing algorithms you accept.
issuerThe iss you expect, or a collection of several you trust.
audienceThe aud you expect, usually your own API's name, or a list of several.
claimsThe token's claims, returned only when every check passes.

The PyJWT documentation on the issuer: "If the issuer claim is incorrect, jwt.InvalidIssuerError will be raised."

The Example​

The example signs one token, issued by https://login.example.org for https://photos.example.org, and decodes it four times: with the right issuer and audience, with the audience of another API, with another issuer, and with neither.

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 signs a token for the photos API and defines check(issuer, audience) calling jwt.decode with both, then checks the right pair, the videos audience, another issuer, and no arguments at all.

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=")

token = jwt.encode(
{
"iss": "https://login.example.org",
"sub": "ada",
"aud": "https://photos.example.org",
"exp": datetime.now(tz=timezone.utc) + timedelta(hours=2),
},
key,
algorithm="HS256",
)


def check(issuer=None, audience=None):
try:
claims = jwt.decode(token, key, algorithms=["HS256"], issuer=issuer, audience=audience)
print(f"accepted: sub {claims['sub']}")
except jwt.InvalidTokenError as err:
print(f"rejected: {type(err).__name__}: {err}")


check("https://login.example.org", "https://photos.example.org")
check("https://login.example.org", "https://videos.example.org")
check("https://other.example.org", "https://photos.example.org")
check()

check passes its arguments straight to jwt.decode. Both default to None, which means "don't check".

Step 3: Run It​

Terminal
uv run main.py
Output
accepted: sub ada
rejected: InvalidAudienceError: Audience doesn't match
rejected: InvalidIssuerError: Invalid issuer
rejected: InvalidAudienceError: Invalid audience

A zsh terminal where uv run main.py prints accepted sub ada, then InvalidAudienceError Audience doesn't match, then InvalidIssuerError Invalid issuer, then InvalidAudienceError Invalid audience.

What Happened​

  • The right issuer and audience passed.
  • The videos audience failed with InvalidAudienceError: Audience doesn't match.
  • Another issuer failed with InvalidIssuerError: Invalid issuer.
  • No issuer and no audience failed too, with InvalidAudienceError: Invalid audience. PyJWT skips the issuer check when issuer is None, but a token that names an audience is only accepted by code that says which audience it is.

That last rule protects you from forgetting the audience check, and it surprises code that worked until the sign-in service started adding aud.

Common Mistakes​

MistakeWhat happensDo this instead
Calling jwt.decode without audience for a token that has audInvalidAudienceError: Invalid audiencePass your API's audience
Turning the check off with options={"verify_aud": False}Tokens made for other APIs passPass the right audience instead
Expecting issuer to be requiredWithout it, any issuer passesPass the issuer you trust

Troubleshooting​

SymptomLikely causeFix
jwt.exceptions.InvalidAudienceError: Invalid audienceThe token has an aud and you passed no audienceAdd audience="..."
jwt.exceptions.InvalidAudienceError: Audience doesn't matchThe token was made for another APICheck which API the token was made for
jwt.exceptions.MissingRequiredClaimError: Token is missing the "aud" claimYou passed audience, but the token has no audHave the sign-in service set an audience

FAQ​

Can I accept several audiences?​

Yes. Pass a list to audience, and the token passes when it names any of them.

What does strict_aud do?​

With options={"strict_aud": True}, PyJWT requires aud to be a single string exactly equal to the one string you pass, and rejects a list in the token.

Conclusion​

Pass issuer= and audience= to jwt.decode on every call. PyJWT then rejects tokens from other issuers and tokens made for other APIs, and it refuses tokens with an aud when you forget to say which audience you are.

Additional Resources​