Developer Tools for Random Data Generation // v2.6.1
root@generate-random:~/jwt-tokens/python$ _

Generate JWT Tokens in Python

Complete code tutorial with examples and best practices

[ Code Example - Quick Summary ]

Language: Python

What: Generate secure JWT tokens in Python using the PyJWT library. Ideal for Django REST Framework, Flask APIs, FastAPI endpoints, and Python microservices authentication.

Try it: Use our interactive Jwt-tokens generator or integrate this code into your Python application.

Generate secure JWT tokens in Python using the PyJWT library. Ideal for Django REST Framework, Flask APIs, FastAPI endpoints, and Python microservices authentication. Looking for other languages? Check our code examples in PHP , JavaScript , Java , C# , C++ , Ruby and Go or use our interactive web generator.

Python Code Example

import jwt
import datetime
import os

# Secret key (store in environment variables)
SECRET_KEY = os.getenv('JWT_SECRET', 'your-256-bit-secret-key')
ISSUER = 'https://yourdomain.com'
AUDIENCE = 'https://yourdomain.com'
ALGORITHM = 'HS256'

# Create token payload
payload = {
    'user_id': 123,
    'username': 'john_doe',
    'role': 'admin',
    'iss': ISSUER,
    'aud': AUDIENCE,
    'iat': datetime.datetime.utcnow(),
    'exp': datetime.datetime.utcnow() + datetime.timedelta(hours=1)
}

# Generate JWT
token = jwt.encode(payload, SECRET_KEY, algorithm=ALGORITHM)
print(token)
# Output: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."

# Decode and verify JWT
try:
    decoded = jwt.decode(
        token,
        SECRET_KEY,
        algorithms=[ALGORITHM],
        issuer=ISSUER,
        audience=AUDIENCE
    )
    print(decoded)
except jwt.ExpiredSignatureError:
    print("Token has expired")
except jwt.InvalidTokenError as e:
    print(f"Invalid token: {e}")

# Flask decorator example
from functools import wraps
from flask import request, jsonify

def token_required(f):
    @wraps(f)
    def decorated(*args, **kwargs):
        token = request.headers.get('Authorization')
        if not token:
            return jsonify({'message': 'Token is missing'}), 401

        try:
            token = token.split(' ')[1]  # Remove "Bearer "
            data = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
        except:
            return jsonify({'message': 'Invalid token'}), 403

        return f(*args, **kwargs)
    return decorated

[EXPLANATION]

PyJWT is the standard JWT library for Python. It supports all common algorithms (HS256, RS256, ES256) and provides comprehensive validation options. Always use datetime.utcnow() for timestamps and validate all claims during decoding. The library automatically handles Base64 URL encoding.

Expected Output

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjoxMjMsInVzZXJuYW1lIjoiam9obl9kb2UiLCJyb2xlIjoiYWRtaW4iLCJpc3MiOiJodHRwczovL3lvdXJkb21haW4uY29tIiwiYXVkIjoiaHR0cHM6Ly95b3VyZG9tYWluLmNvbSIsImlhdCI6MTY4MDAwMDAwMCwiZXhwIjoxNjgwMDAzNjAwfQ.YVPuJ_EqJr8vOT5JkUqHxX9Rj3LmN4K8sQ2TpY6wZ1c

Common Use Cases

  • Django REST Framework authentication
  • Flask-RESTful API authorization
  • FastAPI dependency injection auth
  • Python microservices communication
  • Celery task authentication

Important Notes

  • Install: pip install PyJWT
  • Use algorithms=['HS256'] parameter to prevent algorithm confusion
  • Always validate iss, aud, and exp claims
  • Consider PyJWT[crypto] for RSA/ECDSA support
  • Use djangorestframework-simplejwt for Django projects

Try Our Interactive Generator

Don't want to write code? Use our free web-based Jwt-tokens generator with instant results.

TRY JWT-TOKENS GENERATOR →