Python JWT

4.1.0 · active · verified Tue Apr 14

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

Install

Imports

Quickstart

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}")

view raw JSON →