Python JWT
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.
Warnings
- breaking Version 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.
- gotcha The `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`.
- gotcha JWT 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.
Install
-
pip install python-jwt
Imports
- encode
from jwt import encode
- decode
from jwt import decode
- jwt
import jwt
Quickstart
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}")