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")
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.
JWTs are essential for stateless authentication in modern web applications. This implementation:
pip install pyjwtjwt_manager.py)python jwt_manager.pyTo integrate into your application:
generate_token() to create tokens after successful authenticationvalidate_token() to protect your API endpointsThe 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.