📡 You're offline — showing cached content
New version available!
Quick Access
Tutorials API Design JWT Deep Dive

JWT Deep Dive

5 min read Quiz at the end
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")
Topic Quiz · 1 questions

Test your understanding before moving on

1. What is a JWT refresh token used for?
💡 Refresh tokens are long-lived and used only to obtain new short-lived access tokens when they expire.