JWT Decode vs Verify: Check Signatures and Claims with Python
Understand why decoding a JWT is not verification. Run PyJWT tests for tampering, algorithms, issuer, audience, expiration and required claims.
Decoding a JWT makes its claims readable; accepting those claims requires a trusted verification policy. Verify the cryptographic signature or MAC with a trusted key and allowed algorithm, then validate the issuer, audience, time limits and application requirements. This guide uses invented local tokens and PyJWT to demonstrate failures that a readable payload alone cannot detect.
A readable administrator claim proves very little
A developer copies a token into a decoder, sees a subject and expiration date, and concludes that authentication works. That inspection answers only what the token says. It does not establish who produced it, whether its contents changed, or whether this API is the intended recipient.
The lab below creates a valid token for an invented learner, changes its readable payload to name an administrator, and retains the original signature. An unverified decode still returns the modified subject. The configured verifier rejects the same token because its integrity check fails. No real account, provider or production token is involved.
Keep inspection and acceptance on visibly separate paths. Diagnostic output can help explain a rejected request, but it must not populate an authenticated principal before verification succeeds. Avoid logging full bearer tokens while investigating; a real token can carry access capability and personal information.
Source: PyJWT API: algorithms, required claims and validation options ↗
Separate token structure, cryptographic verification and application policy
This article uses compact signed JWTs with three dot-separated segments: header, payload and signature. The example uses HS256, which applies a shared-key MAC rather than an asymmetric digital signature. JWTs can also use encrypted forms; the three-segment assumption describes this lab, not every JWT representation.
Base64url encoding makes the signed token’s header and payload readable without a decryption key. Signing does not provide confidentiality. Put sensitive information only where your protocol and data-protection requirements permit it; do not treat an unreadable-looking token string as encrypted storage.
Cryptographic verification establishes integrity relative to a selected key and algorithm. It still leaves contextual questions: is the issuer trusted, is the audience this API, is the token currently usable, and does the subject identify an acceptable principal? Authorization then determines what that principal may do to a particular resource.
| Stage | Question answered | Still insufficient for |
|---|---|---|
| Decode structure | Can these bytes be interpreted? | Trusting any claim |
| Verify signature or MAC | Does this token verify under the configured key and algorithm? | Accepting the wrong issuer or audience |
| Validate claims and token purpose | Does it meet this application’s token contract? | Permission to every resource |
| Authorize the operation | May this principal perform this action here? | Replacing verification or session policy |
Source: RFC 7519: JWT representation and registered claims ↗
Choose the key and allowed algorithm from trusted configuration
The verifier fixes algorithms to HS256 alongside its trusted key. It never reads an arbitrary header value and uses that value to build its allowed-algorithm list. A token may identify its algorithm, but that declaration is input to validate against policy rather than permission to select any verification mechanism.
The laboratory key is 64 random bytes generated in memory for each execution. It is neither printed nor a credential to deploy. With symmetric verification, parties possessing that key can also produce tokens. A distributed identity architecture may need asymmetric keys and a provider-specific validation contract instead of distributing a shared secret.
For a real issuer with key rotation, obtain keys through that issuer’s documented, trusted discovery configuration. A received key identifier can help select among approved keys; it must not turn into an unrestricted URL fetch or filesystem lookup. This tutorial does not implement discovery, JWKS caching or rotation.
The rejected HS384 fixture is intentionally signed correctly with the same lab key, yet the application permits only HS256. It demonstrates that a mathematically verifiable token can still violate the configured algorithm policy. The unsigned fixture is rejected as well.
Require claims as well as checking their values
The lab requires iss, aud, sub, exp, nbf and iat. This is the example application’s contract, not a claim that every JWT protocol requires all six. Its issuer is a fixed example.invalid URL and its audience is one API identifier. They are comparison values; the lab makes no network requests.
Requiring a field and validating a present field are different operations. One test signs a token without exp and decodes it using default claim options. That decode succeeds because checking expiration when present does not by itself require expiration to exist. The stricter wrapper rejects the missing exp through its require list.
The wrapper also chooses strict_aud=True, so it accepts the intended single audience string and rejects a list, even a list containing that same audience. Audience arrays are supported by JWT generally; rejecting them here is a deliberate local policy. Adapt that choice to the actual issuer contract rather than treating this fixture as a universal rule.
A subject must additionally be a nonempty string in this application. The library rejects a numeric subject, while the wrapper rejects a whitespace-only one. A correctly typed subject is still only an identifier: map the verified issuer-subject pair to the relevant account and authorization policy.
Source: PyJWT API: algorithms, required claims and validation options ↗
Time checks need a reliable clock and a bounded policy
The lab sets issued-at and not-before to one minute before its current UTC time, with expiration one hour ahead. Separate fixtures put expiration one hour behind or a time claim one hour ahead. These large margins keep the demonstration away from timing-sensitive boundaries without sleeping or disabling validation.
exp limits when a token may be accepted; nbf sets its activation boundary. iat records issuance, and the tested PyJWT version also rejects the future issued-at fixture. Interpret these fields using the protocol and library version actually deployed. An issued-at value is not a substitute for an expiration policy.
Leeway is zero in this lab. Where real systems permit clock skew, choose a small documented allowance and test the boundary cases. Extending leeway until a failing token passes can hide a stale token or clock problem. Fix clock synchronization and inspect the expected time units before changing the acceptance window.
Source: PyJWT usage: unverified inspection and time-claim behavior ↗
Run the complete PyJWT verification lab
Use a disposable Python environment. Install the tested package with python -m pip install "PyJWT==2.15.1", save the script as jwt_validation.py, and run python jwt_validation.py. In the authoring environment, Python 3.12.14 and PyJWT 2.15.1 passed all 27 checks. Review maintained releases before adopting a dependency in a deployed application.
The script generates all tokens locally. It changes no website authentication configuration and uses no real user data. The unverified decode exists only to demonstrate how forged claims remain readable; the verifier always performs its integrity check and the configured claim checks.
The fixture helper expects specific rejection classes, so an unrelated error does not silently count as a successful rejection test. The final ownership comparison is an illustration that authorization remains separate, not an implemented permission system.
"""Invented local JWT fixtures; no provider, web server or real tokens."""
import base64
from datetime import datetime, timezone
import json
import secrets
import jwt
KEY = secrets.token_bytes(64) # ephemeral lab key, never print or deploy it
ISSUER = 'https://issuer.example.invalid'
AUDIENCE = 'example-api'
REQUIRED = ['iss', 'aud', 'sub', 'exp', 'nbf', 'iat']
checks = 0
def check(condition, label):
global checks
checks += 1
if not condition:
raise AssertionError(label)
def verify(token):
claims = jwt.decode(
token, KEY, algorithms=['HS256'],
issuer=ISSUER, audience=AUDIENCE, leeway=0,
options={'require': REQUIRED, 'strict_aud': True,
'enforce_minimum_key_length': True},
)
# Extra application policy: a nonempty subject is mandatory.
if type(claims['sub']) is not str or not claims['sub'].strip():
raise ValueError('Subject must be a nonempty string')
return claims
def expect_rejected(token, exception, label):
try:
verify(token)
except exception:
check(True, label)
else:
raise AssertionError('Accepted: ' + label)
def b64url(data):
return base64.urlsafe_b64encode(data).rstrip(b'=').decode('ascii')
def main():
now = int(datetime.now(timezone.utc).timestamp())
base = {'iss': ISSUER, 'aud': AUDIENCE, 'sub': 'learner-7',
'iat': now - 60, 'nbf': now - 60, 'exp': now + 3600}
def sign(claims, algorithm='HS256', key=KEY):
return jwt.encode(claims, key, algorithm=algorithm)
good = sign(base)
check(verify(good) == base, 'complete valid token accepted')
check(len(good.split('.')) == 3, 'lab uses compact signed JWT')
# Change a readable payload while retaining the old signature.
header, payload, signature = good.split('.')
forged_claims = dict(base, sub='administrator')
forged = '.'.join([header, b64url(json.dumps(forged_claims).encode()), signature])
inspected = jwt.decode(forged, options={'verify_signature': False})
check(inspected['sub'] == 'administrator', 'unverified decode reads modified claim')
expect_rejected(forged, jwt.InvalidSignatureError, 'modified payload')
expect_rejected(sign(base, key=secrets.token_bytes(64)), jwt.InvalidSignatureError,
'wrong signing key')
expect_rejected(sign(base, algorithm='HS384'), jwt.InvalidAlgorithmError,
'validly signed but disallowed algorithm')
unsigned = jwt.encode(base, None, algorithm='none')
expect_rejected(unsigned, jwt.InvalidAlgorithmError, 'unsigned token')
cases = [
({'iss': 'https://other.example.invalid'}, jwt.InvalidIssuerError, 'wrong issuer'),
({'aud': 'other-api'}, jwt.InvalidAudienceError, 'wrong audience'),
({'aud': [AUDIENCE]}, jwt.InvalidAudienceError, 'list audience outside lab policy'),
({'exp': now - 3600}, jwt.ExpiredSignatureError, 'expired'),
({'nbf': now + 3600}, jwt.ImmatureSignatureError, 'not active yet'),
({'iat': now + 3600}, jwt.ImmatureSignatureError, 'future issued-at'),
({'exp': 'invalid'}, jwt.DecodeError, 'bad expiration type/value'),
({'nbf': 'invalid'}, jwt.DecodeError, 'bad not-before type/value'),
({'iat': 'invalid'}, jwt.InvalidIssuedAtError, 'bad issued-at type/value'),
({'sub': 7}, jwt.exceptions.InvalidSubjectError, 'non-string subject'),
({'sub': ' '}, ValueError, 'blank subject rejected by application'),
]
for changes, exception, label in cases:
expect_rejected(sign(dict(base, **changes)), exception, label)
for name in REQUIRED:
claims = dict(base)
del claims[name]
expect_rejected(sign(claims), jwt.MissingRequiredClaimError, 'missing ' + name)
expect_rejected('not-a-jwt', jwt.DecodeError, 'malformed compact token')
# Presence and checking a present expiration are distinct options.
no_exp = dict(base)
del no_exp['exp']
decoded = jwt.decode(sign(no_exp), KEY, algorithms=['HS256'],
issuer=ISSUER, audience=AUDIENCE)
check('exp' not in decoded, 'default expiration checking does not require exp')
# Passing verification is not proof that this user may access any resource.
check(verify(good)['sub'] != 'owner-of-another-resource',
'resource ownership still requires application authorization')
print(f'PASS: {checks} checks; PyJWT {jwt.__version__}')
if __name__ == '__main__':
main()
What the 27 checks establish
A complete valid token passes, and modified payload bytes fail signature verification. A token signed under a different random key also fails. The disallowed algorithm and unsigned cases fail the algorithm policy. These tests exercise actual library operations, not mocked verification results.
Signed tokens with the wrong issuer or audience are rejected, as are the audience-array case, expired token, future activation and future issued-at cases. Invalid time values, a numeric subject, a blank subject, each missing required field and malformed compact input cover additional rejection paths.
The default-options missing-exp test is deliberately accepted outside the strict wrapper to expose a configuration distinction. It is not an invitation to omit expiration. The wrapper’s missing-field tests then demonstrate the intended stricter application contract.
These are local correctness fixtures, not a penetration test or certification of an identity integration. No remote issuer, key rotation, replay store, browser session, revocation service, HTTP middleware or asymmetric algorithm runs here. A passing count describes these cases and this dependency version.
Troubleshoot rejection without weakening the verifier
For an integrity failure, inspect whether the configured key, algorithm and token source match the issuer contract. Confirm that transport has not altered the token and that you are validating the intended token type. Do not work around the error by turning verify_signature off.
For an audience or issuer error, compare verified expectations against the integration documentation. A token issued for another API should remain rejected even when it came from a familiar identity service. Avoid accepting a token’s own issuer claim as the sole authority for choosing which issuer to trust.
For a missing-claim error, determine whether the producer omitted a field required by your API or whether your API applied the wrong contract to a different token purpose. For time errors, compare current UTC, the claim value and the permitted skew. Use sanitized categories and correlation identifiers in operational logs.
Once verification and claim checks pass, investigate authorization independently. A token for learner-7 does not grant access to every learner’s records. Resource ownership, tenant boundaries, roles and allowed actions belong to the application policy, as the related webhook and API-validation guides also illustrate.
A valid token may still be replayed during its allowed lifetime unless the surrounding protocol adds protections. Expiration does not check whether an account was disabled or a token was revoked after issuance. Decide how your application handles those events; the local verifier does not consult session state, account status or a revocation service.
Make the acceptance contract testable
A useful JWT test suite starts with one known valid local fixture, then changes one property at a time: bytes, key, algorithm, issuer, audience, time or claim presence. The resulting rejection explains a specific boundary and makes later configuration changes reviewable.
Keep trusted configuration outside the received token, keep diagnostic decoding outside the authentication path, and preserve the distinction between verified identity and authorized action. Readable claims are a debugging aid; acceptance comes from the complete verification contract.
Your next steps
- Decoded claims remain untrusted until cryptographic verification and contextual checks succeed.
- Configure allowed algorithms and trusted keys together; never derive the allowlist from the token.
- Require mandatory claims explicitly and separately validate their values.
- Test issuer, audience, time and token-purpose policy using the deployed library version.
- JWT validation does not replace resource authorization, replay or revocation policy.
Sources & official resources
Linked resources checked on 2026-11-02. Technical behavior and provider guidance can change; check the documentation for the version you use.
About this guide and its recommendations
Published by Prep With Proof with AI-assisted drafting. Study routines and examples are editorial suggestions, not official exam instructions or claims of a learner's personal results. Cited provider facts are linked; ownership of recommended Prep With Proof products is disclosed. No competitor endorsement or guaranteed certification outcome is implied.
Suggest a correction →