Skip to main content

FastAPI Auth Middleware for Clerk (https://clerk.com)

Project description

FastAPI Clerk Auth Middleware

PyPI version Python Versions License

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 | None = Depends(clerk_auth_guard)):
    return JSONResponse(content=jsonable_encoder(credentials))

The returned credentials model will be either None or an HTTPAuthorizationCredentials object with these properties:

  • scheme: Indicates the scheme of the Authorization header (Bearer)
  • credentials: Raw token received from the Authorization header
  • decoded: The payload of the decoded token

Configuration Options

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", 
    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}"}

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.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

fastapi_clerk_auth-0.0.8.tar.gz (8.6 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

fastapi_clerk_auth-0.0.8-py3-none-any.whl (6.1 kB view details)

Uploaded Python 3

File details

Details for the file fastapi_clerk_auth-0.0.8.tar.gz.

File metadata

  • Download URL: fastapi_clerk_auth-0.0.8.tar.gz
  • Upload date:
  • Size: 8.6 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.11.14

File hashes

Hashes for fastapi_clerk_auth-0.0.8.tar.gz
Algorithm Hash digest
SHA256 82deb6f40f985c0ba9ca59f47aad76f65ce882ce226729714e0b00fdec678479
MD5 8f7a3abede45e5fbfaee59b939549902
BLAKE2b-256 3046581f75011bae19dd83ef1fccee7d5fb18b7a690e4af415a6b99fe73c23a6

See more details on using hashes here.

File details

Details for the file fastapi_clerk_auth-0.0.8-py3-none-any.whl.

File metadata

File hashes

Hashes for fastapi_clerk_auth-0.0.8-py3-none-any.whl
Algorithm Hash digest
SHA256 acc86e8eba465453dd49b3bc738260f9ff071d7feb6819f09a44937a5eef7c70
MD5 28ae1a16a6d5718a283622b6b8f055b6
BLAKE2b-256 e5d8de37309db6739116eb1c09558beb9f45ef836eb807bc9766cb705dbefa73

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page