Create, sign, and verify JWTs with expiry, roles, and refresh token rotation for secure API auth.
JWT — JSON Web Tokens
import jwt, datetime, uuid
SECRET = "your-256-bit-secret"
def create_token(user_id: int, role: str) -> str:
payload = {
"sub": str(user_id),
"role": role,
"iat": datetime.datetime.utcnow(),
"exp": datetime.datetime.utcnow() + datetime.timedelta(hours=1),
"jti": str(uuid.uuid4()),
}
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 Exception("Token expired")
except jwt.InvalidTokenError:
raise Exception("Invalid token")