Python

JWT Sign + Verify (PyJWT)

admin by @admin ADMIN
1d ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
The de-facto JWT library for Python. HS256 demo with an exp claim and the standard "verify everything" decode flow. Mind that PyJWT raises specific exceptions you can catch separately.
Python
Raw
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'}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.