Security utilities
Step 1# pip install pyjwt "pwdlib[argon2]"
from datetime import datetime, timedelta, timezone
import jwt
from pwdlib import PasswordHash
SECRET_KEY = "change-me-in-production-min-32-chars" # load from settings
ALGORITHM = "HS256"
password_hash = PasswordHash.recommended() # Argon2
def hash_password(pw: str) -> str:
return password_hash.hash(pw)
def verify_password(plain: str, hashed: str) -> bool:
return password_hash.verify(plain, hashed)
def create_access_token(user_id: int, expires_min: int = 30) -> str:
expire = datetime.now(timezone.utc) + timedelta(minutes=expires_min)
return jwt.encode({"sub": str(user_id), "exp": expire}, SECRET_KEY, algorithm=ALGORITHM)Tip: The current FastAPI docs use PyJWT and pwdlib. python-jose and passlib, common in older tutorials, are no longer actively maintained.