Python JWT Authentication

Implement JWT authentication in Python using PyJWT with HS256 signing, token verification, expiry validation, and FastAPI dependency injection for protected.

Python Auth Jwt

Code

snippet
import jwt
from datetime import datetime, timedelta, timezone

SECRET = 'your-secret-key'

def create_token(user_id: str) -> str:
    payload = {
        'sub': user_id,
        'exp': datetime.now(timezone.utc) + timedelta(hours=1),
        'iat': datetime.now(timezone.utc),
    }
    return jwt.encode(payload, SECRET, algorithm='HS256')

def verify_token(token: str) -> dict:
    try:
        return jwt.decode(token, SECRET, algorithms=['HS256'])
    except jwt.ExpiredSignatureError:
        raise ValueError('Token expired')
    except jwt.InvalidTokenError:
        raise ValueError('Invalid token')