import jwt # pip install PyJWT
import time
SECRET = "change-me"
def issue_token(user_id: int, ttl_sec: int = 3600) -> str:
payload = {
"sub": str(user_id),
"iat": int(time.time()),
"exp": int(time.time()) + ttl_sec,
"role": "user",
}
return jwt.encode(payload, SECRET, algorithm="HS256")
def verify_token(token: str) -> dict | None:
try:
return jwt.decode(token, SECRET, algorithms=["HS256"])
except jwt.ExpiredSignatureError:
print("token expired")
except jwt.InvalidTokenError as e:
print("invalid:", e)
return None
t = issue_token(42)
print(verify_token(t)) # {'sub': '42', 'iat': …, 'exp': …, 'role': 'user'}
Create a free account and build your private vault. Share publicly whenever you want.