FastAPI Clerk Auth Middleware
A lightweight, easy-to-use authentication middleware for FastAPI that integrates with Clerk authentication services.
This middleware allows you to secure your FastAPI routes by validating JWT tokens against your Clerk JWKS endpoint, making it simple to implement authentication in your API.
Features
- 🔒 Secure API routes with Clerk JWT validation
- 🚀 Simple integration with FastAPI's dependency injection system
- ⚙️ Flexible configuration options (auto error responses, request state access)
- 📝 Decoded token payload accessible in your route handlers
Installation
pip install fastapi-clerk-auth
Basic Usage
from fastapi import FastAPI, Depends
from fastapi_clerk_auth import ClerkConfig, ClerkHTTPBearer, HTTPAuthorizationCredentials
from fastapi.responses import JSONResponse
from fastapi.encoders import jsonable_encoder
app = FastAPI()
# Use your Clerk JWKS endpoint
clerk_config = ClerkConfig(jwks_url="https://your-clerk-frontend-api.clerk.accounts.dev/.well-known/jwks.json")
clerk_auth_guard = ClerkHTTPBearer(config=clerk_config)
@app.get("/")
async def read_root(credentials: HTTPAuthorizationCredentials = Depends(clerk_auth_guard)):
return JSONResponse(content=jsonable_encoder(credentials))
The returned credentials model will be an HTTPAuthorizationCredentials object with these properties:
scheme: Indicates the scheme of the Authorization header (Bearer)credentials: Raw token received from the Authorization headerdecoded: The payload of the decoded token
Configuration Options
Debug Mode
By default, the middleware suppresses exceptions in order to prevent logging sensitive information. You can change this behavior in the ClerkHTTPBearer:
clerk_auth_guard = ClerkHTTPBearer(config=clerk_config, debug_mode=True) # Set debug_mode=True
Fixing Issued At Time (IAT) Errors
In some instances the system clock of an API may be slightly out-of-sync which can cause issues with verifying the iat claim.
This can be solved one of two ways:
1: Disable verifying the iat claim, there could be security implications by disabling so make sure it is secure for your use case.
clerk_config = ClerkConfig(
jwks_url="https://your-clerk-frontend-api.clerk.accounts.dev/.well-known/jwks.json",
verify_iat=False,
)
clerk_auth_guard = ClerkHTTPBearer(config=clerk_config)
2: Adding leeway which is a number of seconds to allow tolerance for drift, it can compensate for out-of-sync clocks.
clerk_config = ClerkConfig(
jwks_url="https://your-clerk-frontend-api.clerk.accounts.dev/.well-known/jwks.json",
leeway=5.0,
)
clerk_auth_guard = ClerkHTTPBearer(config=clerk_config)
Disabling Auto Errors
By default, the middleware automatically returns 403 errors if the token is missing or invalid. You can disable this behavior:
clerk_config = ClerkConfig(
jwks_url="https://your-clerk-frontend-api.clerk.accounts.dev/.well-known/jwks.json"
)
clerk_auth_guard = ClerkHTTPBearer(config=clerk_config, auto_error=False) # Set auto_error=False
This allows requests to reach the endpoint for additional logic or custom error handling:
@app.get("/protected")
async def protected_endpoint(credentials: HTTPAuthorizationCredentials | None = Depends(clerk_auth_guard)):
if not credentials:
return {"message": "You're not authenticated, but you can still see this limited data"}
# Full access for authenticated users
return {"message": "Full access granted", "user_data": credentials.decoded}
Adding Auth Data to Request State
You can have the HTTPAuthorizationCredentials added to the request state for easier access:
from fastapi import Depends, Request, APIRouter
from fastapi_clerk_auth import ClerkConfig, ClerkHTTPBearer, HTTPAuthorizationCredentials
from fastapi.responses import JSONResponse
from fastapi.encoders import jsonable_encoder
clerk_config = ClerkConfig(
jwks_url="https://your-clerk-frontend-api.clerk.accounts.dev/.well-known/jwks.json"
)
clerk_auth_guard = ClerkHTTPBearer(config=clerk_config, add_state=True)
router = APIRouter(prefix="/todo", dependencies=[Depends(clerk_auth_guard)])
@router.get("/")
async def read_todo_list(request: Request):
auth_data: HTTPAuthorizationCredentials = request.state.clerk_auth
user_id = auth_data.decoded.get("sub")
# Use user_id to fetch the user's todo items
return {"message": f"Todo items for user {user_id}"}
The class stored in request.state.clerk_auth looks like this:
HTTPAuthorizationCredentials(
decoded: Optional[dict], # Decoded JWT Token
scheme: str = "Bearer",
credentials: str, # Raw JWT Token
)
Advanced Usage
Role-Based Access Control
You can implement role-based access control by checking the JWT claims:
from fastapi import Depends, HTTPException, status
def admin_required(credentials: HTTPAuthorizationCredentials = Depends(clerk_auth_guard)):
if not credentials:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Not authenticated"
)
user_roles = credentials.decoded.get("roles", [])
if "admin" not in user_roles:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Admin permission required"
)
return credentials
@app.get("/admin", dependencies=[Depends(admin_required)])
async def admin_only():
return {"message": "Welcome, admin!"}
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
License
This project is licensed under the MIT License - see the LICENSE file for details.
Metadata
Release files for fastapi-clerk-auth 0.0.9
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| fastapi_clerk_auth-0.0.9.tar.gz | 14.4 kB | Without provenance | Details for fastapi_clerk_auth-0.0.9.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| fastapi_clerk_auth-0.0.9-py3-none-any.whl | Python 3 | none | any | Details for fastapi_clerk_auth-0.0.9-py3-none-any.whl |
Total release size: 20.8 kB
Release files / fastapi_clerk_auth-0.0.9.tar.gz
| Download URL | fastapi_clerk_auth-0.0.9.tar.gz |
|---|---|
| Size | 14.4 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
503bdd3943e5f49095bd5dd04a8b14ebe6214bb3f39ae45df876e6275db5cf6d
|
|
BLAKE2b-256 checksum How to use checksums |
86af410786fc25e52378df227f4d04e6b43b8c3bc9007221440822e9a10af051
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/6.2.0 CPython/3.11.14
|
Release files / fastapi_clerk_auth-0.0.9-py3-none-any.whl
| Download URL | fastapi_clerk_auth-0.0.9-py3-none-any.whl |
|---|---|
| Size | 6.5 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
f9a47cfc65a2562c144a798ce0022a288799dac1149001b5a109865d578b2647
|
|
BLAKE2b-256 checksum How to use checksums |
794e058ecbe4fa0d470c3979f1272c0199cc47afb0ed935edb07b55441be8994
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/6.2.0 CPython/3.11.14
|
Security for fastapi-clerk-auth 0.0.9
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.