Python Snippets

Generate and Validate JWT Tokens with PyJWT

import jwt
import datetime
from typing import Dict, Any, Optional

class JWTManager:
    def __init__(self, secret_key: str, algorithm: str = "HS256"):
        """
        Initialize JWT Manager with secret key and algorithm.
        
        Args:
            secret_key (str): Secret key for signing tokens
            algorithm (str): Algorithm to use for signing (default: HS256)
        """
        self.secret_key = secret_key
        self.algorithm = algorithm

    def generate_token(self, payload: Dict[str, Any], expires_in: int = 3600) -> str:
        """
        Generate a JWT token with expiration.
        
        Args:
            payload (dict): Data to include in the token
            expires_in (int): Token expiration time in seconds (default: 1 hour)
        
        Returns:
            str: Encoded JWT token
        """
        # Add expiration time to payload
        payload["exp"] = datetime.datetime.utcnow() + datetime.timedelta(seconds=expires_in)
        payload["iat"] = datetime.datetime.utcnow()
        
        # Encode and return token
        return jwt.encode(payload, self.secret_key, algorithm=self.algorithm)

    def validate_token(self, token: str) -> Optional[Dict[str, Any]]:
        """
        Validate and decode a JWT token.
        
        Args:
            token (str): JWT token to validate
        
        Returns:
            dict: Decoded payload if valid, None if invalid
        """
        try:
            # Decode and return payload
            return jwt.decode(token, self.secret_key, algorithms=[self.algorithm])
        except jwt.ExpiredSignatureError:
            print("Token has expired")
            return None
        except jwt.InvalidTokenError:
            print("Invalid token")
            return None

# Example usage
if __name__ == "__main__":
    # Initialize JWT manager
    jwt_manager = JWTManager("my_secret_key")
    
    # Generate a token
    user_data = {
        "user_id": 123,
        "username": "john_doe",
        "role": "admin"
    }
    
    token = jwt_manager.generate_token(user_data, expires_in=1800)  # 30 minutes
    print("Generated Token:", token)
    
    # Validate the token
    payload = jwt_manager.validate_token(token)
    if payload:
        print("Token is valid. Payload:", payload)
    else:
        print("Token validation failed")

Explanation

This code snippet provides a JWT (JSON Web Token) manager class that handles token generation and validation. JWTs are commonly used in web applications for authentication and information exchange between parties.

What It Does

  1. JWTManager Class: Encapsulates JWT operations with configurable secret key and algorithm
  2. Token Generation: Creates signed tokens with automatic expiration handling
  3. Token Validation: Verifies token integrity and checks for expiration
  4. Error Handling: Distinguishes between expired and invalid tokens

Key Features

Why It’s Useful

JWTs are essential for stateless authentication in modern web applications. This implementation:

How to Run

  1. Install the required dependency: pip install pyjwt
  2. Save the code to a file (e.g., jwt_manager.py)
  3. Run directly: python jwt_manager.py

To integrate into your application:

  1. Initialize JWTManager with your secret key
  2. Use generate_token() to create tokens after successful authentication
  3. Use validate_token() to protect your API endpoints
  4. Handle None return values for invalid/expired tokens appropriately

The example demonstrates generating a token for a user with a 30-minute expiration and then validating it. In a real application, you would store the secret key securely (e.g., in environment variables) and use the validation method in middleware or decorators to protect routes.