Python JWT Authentication
Implement JWT authentication in Python using PyJWT with HS256 signing, token verification, expiry validation, and FastAPI dependency injection for protected.
Code
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:
jwtis 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
Basic & Bearer Auth Header ToolEncode and decode HTTP Authorization Basic and Bearer headers locally with UTF-8 Base64 validation and automatic JWT claim and expiry inspection.JWT Expiry CalculatorDecode a JWT payload and convert its exp, iat, and nbf claims into UTC ISO timestamps, with an expired-or-valid verdict.OAuth 2.0 PKCE Code GeneratorGenerate RFC 7636 OAuth 2.0 PKCE code verifiers with Web Crypto CSPRNG, compute SHA-256 code challenges, and build full authorization URLs.JWT Token DecoderDecode JSON Web Token (JWT) headers and payloads safely in the browser. Inspect expiration, issuer, and claims without sending tokens to any external server.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.