Registry / auth-security / jwt
library1.4.0pypypi✓ verified 24d ago

This is a JSON Web Token (JWT) library for Python 3, developed by GehirnInc, providing functionalities to encode and decode JWTs. It leverages the `cryptography` library for handling cryptographic operations, including key loading, signing, and verification. Version 1.4.0 is the latest stable release. It has a steady release cadence, focusing on stability and security rather than rapid feature development.

pip install jwt
INSTALL
IMPORT
SIG · JWT
J
jwt
auth-securitypythonv1.4.0
Install
2.5s avg
Import
90ms
Disk
33MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.93.13
musl
3.93.13
Install & Compatibility
Where this runs
tested against v1.4.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.95 runs
installs and imports cleanly · install 0.0s · import 0.090s · 35.1MB
glibc
py 3.103.95 runs
installs and imports cleanly · install 2.5s · import 0.090s · 36MB
33MB installed
● package 33MB
Code
Verified usage

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

jwt
import jwt
encode
from jwt import encode
decode
from jwt import decode
JWTDecodeError
from jwt.exceptions import JWTDecodeError, JWTVerificationError
Common exceptions for handling decoding failures or verification errors.

This example demonstrates how to encode and decode a JWT using an RSA key pair. It generates an in-memory key pair for illustration. Key elements include specifying the algorithm, handling `datetime` objects in the payload with `datetime_format`, and explicitly listing allowed algorithms and audience during decoding for security.

import jwt import datetime from cryptography.hazmat.primitives import serialization from cryptography.hazmat.primitives.asymmetric import rsa from cryptography.hazmat.backends import default_backend # --- Generate a key pair for demonstration (in a real app, load from secure storage) --- private_key = rsa.generate_private_key( public_exponent=65537, key_size=2048, backend=default_backend() ) public_key = private_key.public_key() # --- Encode a JWT --- payload = { "user_id": 123, "username": "testuser", "exp": datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(minutes=30), "aud": "my-service-audience" } algorithm = "RS256" # For a real application, private_key would be loaded from a secure source. encoded_jwt = jwt.encode( payload, private_key, algorithm=algorithm, headers={"kid": "my_key_id"}, datetime_format="datetime" # Use "datetime" for `datetime` objects in payload ) print("Encoded JWT:", encoded_jwt) # --- Decode a JWT --- # For a real application, public_key would be loaded from a secure source. try: decoded_jwt = jwt.decode( encoded_jwt, public_key, algorithms=[algorithm], # REQUIRED: Must specify allowed algorithms audience="my-service-audience", # RECOMMENDED: Validate audience datetime_format="datetime" ) print("\nDecoded JWT:", decoded_jwt) except jwt.exceptions.JWTDecodeError as e: print(f"\nError decoding JWT: {e}") except Exception as e: print(f"\nAn unexpected error occurred: {e}")
Debug
Known issues
gotchaWhen decoding a JWT, you *must* explicitly provide a list of allowed algorithms (e.g., `algorithms=["RS256"]`) to `jwt.decode()`. Failing to do so will raise a `JWTVerificationError`, which is a critical security measure to prevent "none" algorithm attacks where an attacker could forge a token.
fix
Always pass `algorithms=[...]` with the expected algorithm(s) to `jwt.decode()`.
affects: All versions
gotchaThe library expects specific key types. For symmetric algorithms (e.g., HS256), a `bytes` string secret is required. For asymmetric algorithms (e.g., RS256), `cryptography` key objects (e.g., `RSAPrivateKey` for encoding, `RSAPublicKey` for decoding) are needed. Passing the wrong type or format (e.g., a `str` for an HS256 secret) will lead to errors like `TypeError` or `JWSError`.
fix
Ensure your secret or key is of the correct Python type (`bytes` for symmetric, `cryptography` key object for asymmetric) and format corresponding to the chosen algorithm.
affects: All versions
gotchaBeyond signature verification, critical claims like `audience` (`aud`), `issuer` (`iss`), and `subject` (`sub`) should be explicitly validated during decoding. Use the corresponding arguments in `jwt.decode()` (e.g., `audience="your_app_id"`, `issuer="your_service"`). Failing to validate these can lead to security vulnerabilities such as token reuse or unauthorized access.
fix
Always pass relevant claim validation arguments (e.g., `audience`, `issuer`) to `jwt.decode()` to ensure the token is used in its intended context.
affects: All versions
gotchaAs of v1.4.0, the `datetime_format` parameter was introduced to control how `datetime` objects in payloads are handled. By default, it expects Unix timestamps. If your payload uses Python `datetime.datetime` objects (especially for `exp`, `iat`, `nbf` claims), you must specify `datetime_format="datetime"` in both `jwt.encode()` and `jwt.decode()` to prevent conversion errors or unexpected behavior.
fix
If using `datetime.datetime` objects in your payload claims, set `datetime_format="datetime"` in both `encode` and `decode` calls. Otherwise, ensure `exp`, `iat`, `nbf` claims are Unix timestamps.
affects: >=1.4.0
Errors
Common errors & fixes
ModuleNotFoundError: No module named 'jwt'
This typically occurs when the `python-jwt` library is not installed, or there is a conflict with the `PyJWT` library due to a namespace clash where both packages can be imported as 'jwt'. Developers might have installed `PyJWT` but are trying to use `python-jwt`'s features, or vice-versa, or neither is installed.
fix
Ensure you have the correct library installed. If you intend to use GehirnInc's `python-jwt`, install it via `pip install python-jwt`. If you also have `PyJWT` installed, consider uninstalling both (`pip uninstall jwt PyJWT`) and then reinstalling only the desired one to avoid conflicts. If using `python-jwt`, the import should be `import jwt`.
jwt.exceptions.JWSDecodeError: Signature verification failed
This error is raised when the signature of the JSON Web Token does not match the signature generated using the provided key and algorithm, indicating a wrong key, wrong algorithm, or a tampered token.
fix
Verify that the `key` used for decoding is correct (e.g., the correct secret for HS algorithms, or the public key for RS/ES algorithms) and that the `algorithm` specified in `jwt.decode()` matches the algorithm used during encoding. Ensure the token has not been altered.
jwt.exceptions.ExpiredTokenError: Signature has expired
The JWT contains an `exp` (expiration time) claim, and the current time is past this expiration time (with optional leeway).
fix
Handle the expired token by refreshing it (if using refresh tokens) or prompting the user to re-authenticate. When decoding, you can specify a `leeway` parameter to allow for minor clock skew between systems, e.g., `jwt.decode(token, key, leeway=10, algorithms=['HS256'])` for a 10-second tolerance.
jwt.exceptions.UnsupportedKeyTypeError: could not deserialize
This error indicates that the provided key (especially common with RSA/EC keys) is in an unsupported format, is corrupted, or cannot be properly deserialized by the underlying `cryptography` library.
fix
Ensure the key is in the correct format (e.g., PEM-encoded string for RSA/EC public/private keys) and that it's the appropriate key type (public for verification, private for signing) for the chosen algorithm. Re-generate or re-verify the key's format and content.
jwt.exceptions.InvalidAudienceError: Invalid audience
The `aud` (audience) claim present in the JWT does not match the expected audience value(s) provided during the decoding process, which is a security measure to ensure the token is used by its intended recipient.
fix
When decoding, explicitly pass the expected audience(s) using the `audience` parameter in `jwt.decode()`. For example, `jwt.decode(token, key, audience='your_expected_audience', algorithms=['HS256'])`. Ensure the expected audience exactly matches the `aud` claim in the token.
Upgrade
Version history
1.4.0latest on PyPI · released Jun 23, 2025
Audit
Dependencies
cryptographyrequiredRequired for all cryptographic operations (key loading, signing, verification).
Agent activity
14 hits · last 30 days
node
12
OpenAI (training)
1
Resources