Skip to main content

fastapi-auth-wrapper

A lightweight, plug-and-play authentication wrapper for FastAPI applications that delegate authorization to an external service.

This package allows your FastAPI app to accept incoming requests with an Authorization header, forward the token to a remote authentication service (e.g., a Java backend), and inject a validated user object directly into your route handlers.


✨ Features

  • 🔌 Simple dependency injection (AuthorizedUserClient)
  • 🔐 External token validation (supports microservices architecture)
  • ⚡ Minimal configuration via environment variables
  • 🧩 Clean separation of concerns (FastAPI app vs auth service)
  • 👤 Direct access to authenticated user (client.user)

📦 Installation

pip install fastapi-auth-wrapper

⚙️ Configuration

Set the following environment variables in your application:

AUTH_SERVICE_URL=http://127.0.0.1:8002
AUTH_SERVICE_TOKEN_URL=/auth/user

Explanation

Variable Description
AUTH_SERVICE_URL Base URL of your authentication service
AUTH_SERVICE_TOKEN_URL Endpoint path used to validate tokens (must be POST)

The final request URL will be: AUTH_SERVICE_URL + AUTH_SERVICE_TOKEN_URL


🚀 Quick Start

1. Import the client

from fastapi import FastAPI
from fastapi_auth_wrapper import AuthorizedUserClient

2. Use in your route

app = FastAPI()

@app.get("/check")
async def get_status(client: AuthorizedUserClient):
    print(client.user)
    return {"status": "ok"}

That’s it. The user will be automatically validated and injected.


🔄 How It Works

  1. Incoming request contains:

    Authorization: Bearer <token>
    
  2. The wrapper:

    • Extracts the token

    • Sends a POST request to:

      AUTH_SERVICE_URL + AUTH_SERVICE_TOKEN_URL
      
    • Passes the token for validation

  3. Auth service responds with user data

  4. The wrapper:

    • Parses the response
    • Attaches it to client.user
    • Injects AuthorizedUserClient into your route

👤 Accessing the Authenticated User

Inside any route where AuthorizedUserClient is injected:

@app.get("/profile")
async def profile(client: AuthorizedUserClient):
    user = client.user
    return {
        "user_id": user.get("id"),
        "email": user.get("email")
    }

client.user contains the exact user object returned by your auth service.


🧪 Example Request

GET http://127.0.0.1:8001/check
Content-Type: application/json
Accept: application/json
Authorization: Bearer <your-token>

🧾 Expected Auth Service Behavior

Your external auth service must:

  • Accept a POST request
  • Receive the token (typically via header or body)
  • Validate the token
  • Return a JSON response containing user information

Example Response

{
  "id": "1",
  "email": "user@example.com",
  "roles": ["user"]
}

⚠️ Error Handling

The wrapper will raise appropriate HTTP errors in cases such as:

  • Missing Authorization header
  • Invalid token format
  • Auth service unavailable
  • Token validation failure

You can customize error handling globally in your FastAPI app if needed.


🧩 Use Cases

  • Microservices with centralized authentication
  • FastAPI frontend backed by Java/Spring auth service
  • API gateways needing token verification
  • Multi-client architectures sharing auth

🛠 Advanced Usage

Custom logic using user data

@app.get("/admin")
async def admin_only(client: AuthorizedUserClient):
    if "admin" not in client.user.get("roles", []):
        raise HTTPException(status_code=403, detail="Forbidden")
    return {"message": "Welcome admin"}

🧠 Design Philosophy

  • Keep FastAPI apps lightweight
  • Delegate authentication responsibility
  • Promote reusable infrastructure components

📄 License

MIT License


🙌 Contributing

Contributions, issues, and feature requests are welcome!


📬 Support

If you encounter any issues, feel free to open a GitHub issue or reach out.

Metadata

Release files for fastapi-auth-wrapper 0.1.4

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for fastapi-auth-wrapper 0.1.4
File Size Uploaded
fastapi_auth_wrapper-0.1.4.tar.gz 8.6 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for fastapi-auth-wrapper 0.1.4
File Interpreter ABI Platform
fastapi_auth_wrapper-0.1.4-py3-none-any.whl Python 3 none any Details

Total release size: 16.9 kB

Release files / fastapi_auth_wrapper-0.1.4.tar.gz

Download URL fastapi_auth_wrapper-0.1.4.tar.gz
Size 8.6 kB
Tags Source
SHA-256 checksum
How to use checksums
01be335388f5ded8fa9d083e851d9340897997b61c3575e5b17ded1e2b1f87cc
BLAKE2b-256 checksum
How to use checksums
0d0760666747d76227d3c5325b5a7e359fccd6f3e0cbe11ec104f8014b7b0327
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.12.12

Release files / fastapi_auth_wrapper-0.1.4-py3-none-any.whl

Download URL fastapi_auth_wrapper-0.1.4-py3-none-any.whl
Size 8.3 kB
Tags Python 3
SHA-256 checksum
How to use checksums
0c15baa51b81a69e04b3a0de369e86049b140981c87632760296f0cd72083e0d
BLAKE2b-256 checksum
How to use checksums
c03acc0049924c426dc24aeeb43a819d437ac9bb950fa4d019db8942723d6d4e
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.12.12

Release history Release notifications | RSS feed

This release

0.1.4 This release

2 release files

0.1.3

2 release files

0.1.2

2 release files

0.1.1

2 release files

0.1.0

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page