Skip to main content

This is a FastAPI wrapper

Project description

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.

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_auth_wrapper-0.1.0.tar.gz (8.1 kB view details)

Uploaded Source

Built Distribution

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

fastapi_auth_wrapper-0.1.0-py3-none-any.whl (8.1 kB view details)

Uploaded Python 3

File details

Details for the file fastapi_auth_wrapper-0.1.0.tar.gz.

File metadata

  • Download URL: fastapi_auth_wrapper-0.1.0.tar.gz
  • Upload date:
  • Size: 8.1 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.12

File hashes

Hashes for fastapi_auth_wrapper-0.1.0.tar.gz
Algorithm Hash digest
SHA256 4073b2e463e6c0359124c8e10c1057f42f7ea2002d1c61954db8457fd3a3eda3
MD5 97c5a00edad21ac50b1f590e0cf0e6ff
BLAKE2b-256 c2f0dae6cd87b4796d4e0c5787706db7c7262e5466801d656884484fb151c6c0

See more details on using hashes here.

File details

Details for the file fastapi_auth_wrapper-0.1.0-py3-none-any.whl.

File metadata

File hashes

Hashes for fastapi_auth_wrapper-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 415d4ff64401b7b491bd8c44649ac4c5f491b9e76a0de592f8deef57f3d10b3f
MD5 3796954a1c9995fddb1101f91f3cfc1a
BLAKE2b-256 3f0b3fe0cae1c4c77c57e04a8fa2ecd6617620663af115ad1d8524efc9470b9a

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