DEV Community

Cover image for JWT Pro: A Python Package for Secure JWT Generation and Verification
Krishna Tadi
Krishna Tadi

Posted on

JWT Pro: A Python Package for Secure JWT Generation and Verification

JWT Pro - JWT Generation & Verification with AES Encryption

Welcome to JWT Pro, your go-to Python package for creating and verifying JSON Web Tokens (JWTs). With support for AES encryption and HMAC signatures, it ensures your user authentication and data transmission are as secure as possible. The package is highly customizable, letting you tweak encryption settings, headers, payloads and validation to fit your needs perfectly.


Features

  • JWT Generation: Create JSON Web Tokens with optional AES encryption.
  • HMAC Signatures: Secure token signatures using HMAC with customizable algorithms.
  • Expiration Handling: Automatic expiration handling with timestamp-based validation.
  • Customizable Headers & Payload: Flexible header and payload creation.
  • Encryption Option: AES encryption for protecting sensitive data in the payload.
  • Token Verification: Validate tokens and verify signatures with proper error handling.

Benefits

  • Security: Ensures secure data transmission with AES encryption.
  • Ease of Use: Simple API for token generation and verification.
  • Customization: Flexible header and payload structures allow custom implementations.
  • Scalability: Suitable for scalable applications with token-based authentication.
  • Reliability: Automatic expiration checks and error handling for invalid tokens.

Installation

This package is available through the PyPI registry.

Before installing, ensure you have Python 3.6 or higher installed. You can download and install Python from python.org.

You can install the package using pip:

pip install jwt-pro

Enter fullscreen mode Exit fullscreen mode

Methods

Method Description
generate_token() Generates a JWT with a custom header, payload, and optional encryption.
verify_token() Verifies a JWT token and checks its validity, expiration, and integrity.

Encrypt Option (encrypt=True vs encrypt=False)

The encrypt parameter in the generate_token() and verify_token() methods controls whether the payload is encrypted using AES. Here’s how it behaves:

encrypt Parameter Behavior Use Case
encrypt=True - The payload is encrypted using AES with CBC mode. Use when sensitive data in the payload needs to be protected.
- The token payload is stored in encrypted form and cannot be read directly. Ideal for protecting data like passwords, user data, etc.
encrypt=False - The payload is stored in plain text (unencrypted). Use when the data in the payload does not require encryption.
- The payload can be directly read and is visible in the token. Suitable for non-sensitive, public data (e.g., user ID, session info).

Installation

Importing the Package

from jwt_pro import generate_token, verify_token
Enter fullscreen mode Exit fullscreen mode

Generate a JWT (Without Encryption)

from jwt_pro import generate_token

# Define Header and Payload
header = {
    "alg": "HS256",  # HMAC-SHA256 algorithm
    "typ": "JWT"
}
payload = {
    "user_id": "12345",
    "name": "John Doe"
}
secret = "your-secret-key"
expiry = 3600 (default 3600)

## Generate JWT (without encryption)
token = generate_token(header, payload, secret, expiry, encrypt=False)

print(f"Generated Token: {token}")
Enter fullscreen mode Exit fullscreen mode

Verify a JWT (Without Encryption)

from jwt_pro import verify_token

# Secret key used for signing
secret = "your-secret-key"

# Token to verify (use token from previous example)
token = "eyJhbGciOiAiSFMyNTYiLCAidHlwIjogIkpXVCJ9..."

try:
    verified_payload = verify_token(token, secret, encrypt=False)
    print(f"Verified Payload: {verified_payload}")
except ValueError as e:
    print(f"Verification Error: {e}")
Enter fullscreen mode Exit fullscreen mode

Generate JWT with AES Encryption

from jwt_pro import generate_token

# Define Header and Payload
header = {
    "alg": "HS256",  # HMAC-SHA256 algorithm
    "typ": "JWT"
}
payload = {
    "user_id": "12345",
    "name": "John Doe"
}
secret = "your-secret-key"

# Generate JWT with AES encryption
token_encrypted = generate_token(header, payload, secret, expires_in=3600, encrypt=True)

print(f"Generated Encrypted Token: {token_encrypted}")
Enter fullscreen mode Exit fullscreen mode

Verify Encrypted JWT

from jwt_pro import verify_token

# Secret key used for signing
secret = "your-secret-key"

# Encrypted token to verify (use token from previous example)
token_encrypted = "eyJhbGciOiAiSFMyNTYiLCAidHlwIjogIkpXVCJ9..."

try:
    verified_payload_encrypted = verify_token(token_encrypted, secret, encrypt=True)
    print(f"Verified Encrypted Payload: {verified_payload_encrypted}")
except ValueError as e:
    print(f"Verification Error: {e}")
Enter fullscreen mode Exit fullscreen mode

Token Expiration

The default expiration time for the token is 1 hour (3600 seconds). If not explicitly specified during token generation, the token will automatically expire 1 hour from the time it was created.

You can change the expiration time by passing the expiry claim during the token generation process.

from jwt_pro import generate_token
token = generate_token(payload, secret, expiry=7200)  # Token will expire in 2 hours

Enter fullscreen mode Exit fullscreen mode

Common Errors

Error Type Description
ValueError: Token has expired. Raised when the token has expired based on the exp field.
ValueError: Invalid token format. Raised when the token format does not match the expected header.payload.signature format.
ValueError: Invalid token header. Raised when the header is malformed or missing required fields.
ValueError: Invalid token payload. Raised when the payload cannot be decrypted or parsed.
ValueError: Unsupported algorithm. Raised if the algorithm specified in the token header is unsupported.

Use Cases

  • User Authentication: Securely authenticate users in web applications by generating and verifying tokens.
  • Data Protection: Encrypt sensitive data in the token payload and ensure its integrity during transmission.
  • Session Management: Manage user sessions using JWTs with automatic expiration handling.
  • API Authentication: Secure communication between microservices using JWTs for API authentication.

Discussions

  • GitHub Discussions: Share use cases, report bugs, and suggest features.

We'd love to hear from you and see how you're using JWT PRO in your projects!


Requesting Features

If you have an idea for a new feature, please open a feature request in the Issues section with:

  • A clear description of the feature
  • Why it would be useful

Issues and Feedback

For issues, feedback, and feature requests, please open an issue on our GitHub Issues page. We actively monitor and respond to community feedback.


Join Our Growing Developer Community

We invite developers from all backgrounds to contribute, provide feedback, and help shape the future of password security.

🔗 GitHub: GitHub
💬 Discussions: Engage with other developers and share ideas.
🚀 Suggest Features: Have an idea? We're always looking to improve.
⭐ Give us a star on GitHub to support the project!
📧 Issues: Share your experiences and suggestions through GitHub discussions or report issues to help us improve further.
NPM Issues, PYPI Issues

Become a part of our community and let’s build secure applications together!


FAQ (Frequently Asked Questions)

For detailed answers to common questions, click here to visit our FAQ section.


License

This project is licensed under the MIT License. See the LICENSE file for details.

Image of Datadog

The Essential Toolkit for Front-end Developers

Take a user-centric approach to front-end monitoring that evolves alongside increasingly complex frameworks and single-page applications.

Get The Kit

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more