Registry / auth-security / python-jwt

python-jwt

JSON →
library4.1.0pypypi✓ verified 85d ago

python-jwt is a Python module for generating and verifying JSON Web Tokens (JWTs). It leverages the `cryptography` library for cryptographic operations and provides a straightforward API for encoding and decoding tokens. The current version is 4.1.0, with an intermittent, feature-driven release cadence.

pip install python-jwt
INSTALL
IMPORT
SIG · PYTHON-JWT
P
python-jwt
auth-securitypythonv4.1.0
Install
2.5s avg
Import
Disk
34MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.93.13
musl
3.93.13
Install & Compatibility
Where this runs
tested against v4.1.0 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.103.920 runs
installs and imports cleanly · install 0.0s · import 0.000s · 35MB
glibc
py 3.103.920 runs
installs and imports cleanly · install 2.5s · import 0.000s · 35MB
34MB installed
● package 34MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

generate_jwt
from python_jwt import generate_jwt
from jwt import encode
verify_jwt
from python_jwt import verify_jwt
from jwt import decode
JWS
from python_jwt import JWS
from jwt import JWS

This example demonstrates how to encode a JWT with a payload and secret key, and then decode it, including basic error handling for common JWT exceptions. Remember to use a strong, securely stored secret key in production.

import jwt import datetime # Your secret key for signing the token secret_key = "your-super-secret-key-that-should-be-kept-safe" # Define the token payload with an expiry time payload = { 'user_id': 123, 'username': 'testuser', 'exp': datetime.datetime.utcnow() + datetime.timedelta(minutes=30), 'iat': datetime.datetime.utcnow() } # Encode the token using HS256 algorithm token = jwt.encode(payload, secret_key, algorithm='HS256') print(f"Encoded Token: {token}") # Decode the token, specifying the expected algorithm try: decoded_payload = jwt.decode(token, secret_key, algorithms=['HS256']) print(f"Decoded Payload: {decoded_payload}") except jwt.exceptions.ExpiredSignatureError: print("Error: Token has expired!") except jwt.exceptions.InvalidTokenError as e: print(f"Error: Invalid Token - {e}")
Debug
Known issues
breakingVersion 4.0.0 introduced a hard dependency on `cryptography` version 3.x.x or higher. If you were using an older version of `cryptography`, upgrading `python-jwt` to 4.x will likely require upgrading `cryptography` as well.
fix
Ensure your `cryptography` dependency is updated to `cryptography>=3.0.0`. If using `pip`, `pip install --upgrade python-jwt cryptography` should resolve it.
affects: >=4.0.0
gotchaThe `jwt.decode()` function requires an `algorithms` parameter, which must be a list of allowed algorithms (e.g., `['HS256']`). Passing a single string (e.g., `algorithm='HS256'`) will result in a `TypeError`.
fix
Always pass `algorithms` as a list: `jwt.decode(token, key, algorithms=['HS256'])`.
affects: All versions
gotchaJWT validation, especially for expiry (`exp`), not-before (`nbf`), audience (`aud`), and issuer (`iss`) claims, is crucial. While `python-jwt` handles these by default if present in the payload and `verify_claims=True` (default), you must handle `ExpiredSignatureError` and `InvalidTokenError` during decoding.
fix
Wrap your `jwt.decode()` calls in `try...except jwt.exceptions.ExpiredSignatureError` and `try...except jwt.exceptions.InvalidTokenError` blocks to gracefully handle invalid or expired tokens.
affects: All versions
Upgrade
Version history
4.1.0latest on PyPI · released Nov 13, 2023
Audit
Dependencies
cryptographyrequiredProvides the underlying cryptographic primitives for JWT signing and verification. Required since version 2.0.
Agent activity
31 hits · last 30 days
node
30
OpenAI (training)
1
Resources
python-jwt — pip install python-jwt · libregistry