Token Generation
Secure token generation using cryptographically strong random values with configurable expiration and scopes.
Validation
Fast token validation with caching, signature verification, and expiration checking.
Refresh Strategy
Automatic token refresh with sliding expiration and secure refresh token rotation.
Token Implementation
token_manager.py
# JWT Token Management
import jwt
from datetime import datetime, timedelta
class TokenManager:
def __init__(self, secret_key, algorithm="HS256"):
self.secret = secret_key
self.algorithm = algorithm
def generate_token(self, user_id, scopes, ttl=3600):
payload = {
"sub": user_id,
"scopes": scopes,
"iat": datetime.utcnow(),
"exp": datetime.utcnow() + timedelta(seconds=ttl)
}
return jwt.encode(payload, self.secret, algorithm=self.algorithm)
def validate_token(self, token):
try:
return jwt.decode(token, self.secret, algorithms=[self.algorithm])
except jwt.ExpiredSignatureError:
return None
Token Lifecycle
STEP 1
Request
STEP 2
Validate
STEP 3
Generate
STEP 4
Return