{"id":15044048,"url":"https://github.com/ossmafia/fastapi-clerk-middleware","last_synced_at":"2025-10-23T20:30:17.755Z","repository":{"id":253056335,"uuid":"842323364","full_name":"OSSMafia/fastapi-clerk-middleware","owner":"OSSMafia","description":"FastAPI Auth Middleware for Clerk (https://clerk.com)","archived":false,"fork":false,"pushed_at":"2024-09-09T00:10:09.000Z","size":20,"stargazers_count":13,"open_issues_count":1,"forks_count":0,"subscribers_count":2,"default_branch":"main","last_synced_at":"2025-01-30T20:40:50.164Z","etag":null,"topics":["authentication","clerk","clerk-auth","clerk-authentication","clerkauth","fastapi","jwks","python"],"latest_commit_sha":null,"homepage":"","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/OSSMafia.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2024-08-14T05:49:30.000Z","updated_at":"2025-01-22T21:27:11.000Z","dependencies_parsed_at":"2024-09-09T01:24:58.654Z","dependency_job_id":"f117d0fa-4555-4685-9d69-02dc90861090","html_url":"https://github.com/OSSMafia/fastapi-clerk-middleware","commit_stats":null,"previous_names":["ossmafia/fastapi-clerk-middleware"],"tags_count":4,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/OSSMafia%2Ffastapi-clerk-middleware","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/OSSMafia%2Ffastapi-clerk-middleware/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/OSSMafia%2Ffastapi-clerk-middleware/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/OSSMafia%2Ffastapi-clerk-middleware/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/OSSMafia","download_url":"https://codeload.github.com/OSSMafia/fastapi-clerk-middleware/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":237882172,"owners_count":19381176,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["authentication","clerk","clerk-auth","clerk-authentication","clerkauth","fastapi","jwks","python"],"created_at":"2024-09-24T20:50:00.136Z","updated_at":"2025-10-23T20:30:17.746Z","avatar_url":"https://github.com/OSSMafia.png","language":"Python","funding_links":[],"categories":[],"sub_categories":[],"readme":"# FastAPI Clerk Auth Middleware\n\n[![PyPI version](https://img.shields.io/pypi/v/fastapi-clerk-auth.svg)](https://pypi.org/project/fastapi-clerk-auth/)\n[![Python Versions](https://img.shields.io/pypi/pyversions/fastapi-clerk-auth.svg)](https://pypi.org/project/fastapi-clerk-auth/)\n[![License](https://img.shields.io/github/license/OSSMafia/fastapi-clerk-middleware)](https://github.com/OSSMafia/fastapi-clerk-middleware/blob/main/LICENSE)\n\nA lightweight, easy-to-use authentication middleware for [FastAPI](https://fastapi.tiangolo.com/) that integrates with [Clerk](https://clerk.com) authentication services.\n\nThis 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.\n\n## Features\n\n- 🔒 Secure API routes with Clerk JWT validation\n- 🚀 Simple integration with FastAPI's dependency injection system\n- ⚙️ Flexible configuration options (auto error responses, request state access)\n- 📝 Decoded token payload accessible in your route handlers\n\n## Installation\n\n```bash\npip install fastapi-clerk-auth\n```\n\n## Basic Usage\n\n```python\nfrom fastapi import FastAPI, Depends\nfrom fastapi_clerk_auth import ClerkConfig, ClerkHTTPBearer, HTTPAuthorizationCredentials\nfrom fastapi.responses import JSONResponse\nfrom fastapi.encoders import jsonable_encoder\n\napp = FastAPI()\n\n# Use your Clerk JWKS endpoint\nclerk_config = ClerkConfig(jwks_url=\"https://your-clerk-frontend-api.clerk.accounts.dev/.well-known/jwks.json\") \n\nclerk_auth_guard = ClerkHTTPBearer(config=clerk_config)\n\n@app.get(\"/\")\nasync def read_root(credentials: HTTPAuthorizationCredentials | None = Depends(clerk_auth_guard)):\n    return JSONResponse(content=jsonable_encoder(credentials))\n```\n\nThe returned `credentials` model will be either `None` or an `HTTPAuthorizationCredentials` object with these properties:\n\n- `scheme`: Indicates the scheme of the Authorization header (Bearer) \n- `credentials`: Raw token received from the Authorization header\n- `decoded`: The payload of the decoded token\n\n## Configuration Options\n\n### Disabling Auto Errors\n\nBy default, the middleware automatically returns 403 errors if the token is missing or invalid. You can disable this behavior:\n\n```python\nclerk_config = ClerkConfig(\n    jwks_url=\"https://your-clerk-frontend-api.clerk.accounts.dev/.well-known/jwks.json\", \n    auto_error=False\n)\n```\n\nThis allows requests to reach the endpoint for additional logic or custom error handling:\n\n```python\n@app.get(\"/protected\")\nasync def protected_endpoint(credentials: HTTPAuthorizationCredentials | None = Depends(clerk_auth_guard)):\n    if not credentials:\n        return {\"message\": \"You're not authenticated, but you can still see this limited data\"}\n    \n    # Full access for authenticated users\n    return {\"message\": \"Full access granted\", \"user_data\": credentials.decoded}\n```\n\n### Adding Auth Data to Request State\n\nYou can have the `HTTPAuthorizationCredentials` added to the request state for easier access:\n\n```python\nfrom fastapi import Depends, Request, APIRouter\nfrom fastapi_clerk_auth import ClerkConfig, ClerkHTTPBearer, HTTPAuthorizationCredentials\nfrom fastapi.responses import JSONResponse\nfrom fastapi.encoders import jsonable_encoder\n\nclerk_config = ClerkConfig(\n    jwks_url=\"https://your-clerk-frontend-api.clerk.accounts.dev/.well-known/jwks.json\"\n) \n\nclerk_auth_guard = ClerkHTTPBearer(config=clerk_config, add_state=True)\n\nrouter = APIRouter(prefix=\"/todo\", dependencies=[Depends(clerk_auth_guard)])\n\n@router.get(\"/\")\nasync def read_todo_list(request: Request):\n    auth_data: HTTPAuthorizationCredentials = request.state.clerk_auth\n    user_id = auth_data.decoded.get(\"sub\")\n    \n    # Use user_id to fetch the user's todo items\n    return {\"message\": f\"Todo items for user {user_id}\"}\n```\n\n## Advanced Usage\n\n### Role-Based Access Control\n\nYou can implement role-based access control by checking the JWT claims:\n\n```python\nfrom fastapi import Depends, HTTPException, status\n\ndef admin_required(credentials: HTTPAuthorizationCredentials = Depends(clerk_auth_guard)):\n    if not credentials:\n        raise HTTPException(\n            status_code=status.HTTP_401_UNAUTHORIZED,\n            detail=\"Not authenticated\"\n        )\n    \n    user_roles = credentials.decoded.get(\"roles\", [])\n    if \"admin\" not in user_roles:\n        raise HTTPException(\n            status_code=status.HTTP_403_FORBIDDEN,\n            detail=\"Admin permission required\"\n        )\n    \n    return credentials\n\n@app.get(\"/admin\", dependencies=[Depends(admin_required)])\nasync def admin_only():\n    return {\"message\": \"Welcome, admin!\"}\n```\n\n## Contributing\n\nContributions are welcome! Please feel free to submit a Pull Request.\n\n## License\n\nThis project is licensed under the MIT License - see the LICENSE file for details.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fossmafia%2Ffastapi-clerk-middleware","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fossmafia%2Ffastapi-clerk-middleware","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fossmafia%2Ffastapi-clerk-middleware/lists"}