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 jwtVerified import paths — ran on the pinned version, not inferred.
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.
Always pass `algorithms=[...]` with the expected algorithm(s) to `jwt.decode()`.
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.
Always pass relevant claim validation arguments (e.g., `audience`, `issuer`) to `jwt.decode()` to ensure the token is used in its intended context.
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.
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`.
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.
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.
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.
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.