PyJWT library with PyJWKClient for JWKS fetching.
Installation
Install the required dependencies:flask: Web frameworkPyJWT: JWT encoding/decoding and verificationcryptography: Required for EdDSA (Ed25519) signature verification
Basic Example
Here’s a complete Flask application with JWT verification:app.py
Middleware Pattern
For more complex applications, create a reusable auth middleware:auth/middleware.py
app.py
FastAPI Example
If you’re using FastAPI instead of Flask:main.py
Error Handling
Handle different JWT error cases:auth/errors.py
Configuration Management
Use a config class for better organization:config.py
Testing
Test your JWT verification:test_auth.py
Environment Variables
Create a.env file for development:
.env
python-dotenv:
app.py
Production Deployment
For production, use a production-grade WSGI server like Gunicorn:Procfile for platforms like Heroku:
Docker Example
Create aDockerfile:
Dockerfile
requirements.txt:
Common Issues
ModuleNotFoundError: No module named 'cryptography'
ModuleNotFoundError: No module named 'cryptography'
The
cryptography package is required for EdDSA signature verification:'invalid signature' error
'invalid signature' error
Verify that:
- JWKS URL is correct and accessible
- Token was issued by the correct Better Auth instance
- Issuer and audience match your configuration
Token expired errors
Token expired errors
JWTs have limited lifetime. Ensure your frontend refreshes tokens before expiration. The
api-client.ts handles this with a 10-second buffer.CORS errors in development
CORS errors in development
If your frontend and backend are on different ports, enable CORS:
Next Steps
Go Example
See how to implement JWT verification in Go
Express Example
Learn how to verify JWTs in Express.js with jose