Python JWT Authentication

Implement JWT authentication in Python using PyJWT with HS256 signing, token verification, expiry validation, and FastAPI dependency injection for protected.

PythonAuth Jwt

Code

snippet
import jwt
from datetime import datetime, timedelta, timezone

SECRET = 'your-secret-key'

def create_token(user_id: str) -> str:
    payload = {
        'sub': user_id,
        'exp': datetime.now(timezone.utc) + timedelta(hours=1),
        'iat': datetime.now(timezone.utc),
    }
    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 ValueError('Token expired')
    except jwt.InvalidTokenError:
        raise ValueError('Invalid token')

What the code does

All of the logic lives in the functions create_token and verify_token.

datetime, timedelta, timezone are the only symbols borrowed from jwt — the coupling is explicit and narrow. ValueError appears at a raise inside an except handler — it fires only while that failure type is already being handled.

What to watch for

  • Plan for an install step: jwt is a real dependency, resolved by the package manager.

Applying it

The primary signature is def create_token(user_id: str) -> str

The surface worth importing is create_token; the helpers around it are private to the snippet.

Statements that matter

def create_token(user_id: str) -> str:
    payload = {
        'sub': user_id,
        'exp': datetime.now(timezone.utc) + timedelta(hours=1),
        'iat': datetime.now(timezone.utc),
    }
    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 ValueError('Token expired')
    except jwt.InvalidTokenError:
        raise ValueError('Invalid token')

Interactive Tools for This Topic

FAQ

When is the exception raised?
Inside an `except` handler — the `ValueError` fires only while that failure type is already being handled, not on its own trigger.
Which packages must be installed first?
Yes. The imports resolve to `jwt`, which the package manager must provide.