Skip to main content

Role-based access control with contextual authorization for FastAPI

Project description

fastapi-rbac-authz

Role-based access control with contextual authorization for FastAPI.

Installation

pip install fastapi-rbac-authz

Quick Start

from typing import Annotated
from fastapi import Depends, FastAPI
from fastapi_rbac import (
    RBACAuthz, RBACRouter, Global, Contextual, ContextualAuthz, RBACUser
)

# 1. Define your user model
class User:
    def __init__(self, user_id: str, roles: set[str]):
        self.user_id = user_id
        self.roles = roles

# 2. Define role permissions
PERMISSIONS = {
    "admin": {
        Global("report:*"),         # Admin can do anything with reports
    },
    "viewer": {
        Contextual("report:read"),  # Viewer needs context check
    },
}

# 3. Create a context check (for contextual permissions)
# All __init__ params are injected by FastAPI's DI system
class ReportAccessContext(ContextualAuthz[User]):
    def __init__(
        self,
        report_id: int,  # <-- Injected from path parameter
        user: Annotated[User, Depends(RBACUser)],
    ):
        self.user = user
        self.report_id = report_id

    async def has_permissions(self) -> bool:
        # Your logic: check if user can access this specific report
        allowed_reports = {1, 2, 3}  # e.g., query from database
        return self.report_id in allowed_reports

# 4. Create your app and configure RBAC
app = FastAPI()

async def get_current_user() -> User:
    # Your authentication logic here
    return User(user_id="user-1", roles={"viewer"})

RBACAuthz(
    app,
    get_roles=lambda u: u.roles,
    permissions=PERMISSIONS,
    user_dependency=get_current_user,
    ui_path="/_rbac",  # Optional: mount visualization UI
)

# 5. Create protected routes
router = RBACRouter(permissions={"report:read"}, contexts=[ReportAccessContext])

@router.get("/reports/{report_id}")
async def get_report(report_id: int):
    return {"report_id": report_id}

@router.post("/reports", permissions={"report:create"})  # Override permissions
async def create_report():
    return {"id": "new-report"}

app.include_router(router, prefix="/api")

Permission Scopes

Permissions can be granted with two scopes:

Global Scope

Global("report:read")

Global permissions bypass context checks entirely. If a user has a global permission, they can access the resource without any additional validation. Use this for admin roles or service accounts that need unrestricted access.

Contextual Scope

Contextual("report:read")

Contextual permissions require context checks to pass. The user must have the permission AND the context check must return True. Use this for regular users who should only access resources they own or are members of.

Example

PERMISSIONS = {
    "admin": {
        Global("report:*"),         # Can access ALL reports, no questions asked
    },
    "user": {
        Contextual("report:read"),  # Can only read reports they have access to
        Contextual("report:create"),
    },
}

Context Checks

Context checks are classes that implement fine-grained authorization logic. They're regular FastAPI dependencies, so you can inject any parameters (path params, query params, request body, database sessions, etc.).

class ReportAccessContext(ContextualAuthz[User]):
    def __init__(
        self,
        report_id: int,  # Injected from path parameter
        user: Annotated[User, Depends(RBACUser)],
        db: Annotated[AsyncSession, Depends(get_db)],  # Database session
    ):
        self.user = user
        self.report_id = report_id
        self.db = db

    async def has_permissions(self) -> bool:
        # Query database to check if user can access this report
        report = await self.db.get(Report, self.report_id)
        return report is not None and report.owner_id == self.user.user_id

Authorization Flow

When a request hits an RBAC-protected endpoint:

1. Authentication
   └── user_dependency runs → User object available

2. Permission Check
   └── Does user have ANY grant (global or contextual) for required permission?
       ├── No  → 403 Forbidden
       └── Yes → Continue

3. Scope Evaluation
   └── Is the grant Global?
       ├── Yes → Access granted (skip context checks)
       └── No  → Continue to context checks

4. Context Checks (only for Contextual grants)
   └── Run all context classes via FastAPI DI
       └── Do ALL contexts return True?
           ├── No  → 403 Forbidden
           └── Yes → Access granted

5. Endpoint Handler Executes

Wildcard Permissions

Use wildcards to grant multiple permissions at once:

Grant Implies
* Everything
report:* report:read, report:create, report:delete, etc.
report:metrics:* report:metrics:view, report:metrics:export, etc.
PERMISSIONS = {
    "admin": {Global("*")},              # Full access to everything
    "reporter": {Global("report:*")},    # Full access to reports only
}

Running the Example

A complete runnable example is included in the examples/ directory:

# Install dependencies
pip install fastapi-rbac-authz uvicorn

# Run the example
uvicorn examples.basic_app:app --reload

Then open your browser:

Test with different users

The example uses X-Token header for authentication:

# As admin (has Global("*") - full access)
curl -H "X-Token: admin-token" http://localhost:8000/reports
curl -H "X-Token: admin-token" http://localhost:8000/reports/1

# As user (has Contextual permissions - can only access own reports)
curl -H "X-Token: user-token" http://localhost:8000/reports/1  # OK (owns report 1)
curl -H "X-Token: user-token" http://localhost:8000/reports/3  # 403 (doesn't own report 3)

# As viewer (has Contextual read - can only read own reports)
curl -H "X-Token: viewer-token" http://localhost:8000/reports/1  # 403 (doesn't own any)

Visualization UI

Mount the built-in visualization UI to explore your authorization schema:

RBACAuthz(
    app,
    # ...
    ui_path="/_rbac",
)

Visit /_rbac to see an interactive graph showing:

  • Roles and their permission grants
  • Permissions with scope indicators (global/contextual)
  • Endpoints and their required permissions
  • Context checks and which endpoints use them

Double-click any node to isolate and explore its relationships.

Screenshots

Full authorization graph

Full Graph

Role isolation view - double-click a role to see what it can access

Role Isolation

Endpoint isolation view - double-click an endpoint to see who can access it

Endpoint Isolation

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_rbac_authz-0.2.0.tar.gz (64.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_rbac_authz-0.2.0-py3-none-any.whl (29.7 kB view details)

Uploaded Python 3

File details

Details for the file fastapi_rbac_authz-0.2.0.tar.gz.

File metadata

  • Download URL: fastapi_rbac_authz-0.2.0.tar.gz
  • Upload date:
  • Size: 64.6 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/2.3.2 CPython/3.13.2 Darwin/25.2.0

File hashes

Hashes for fastapi_rbac_authz-0.2.0.tar.gz
Algorithm Hash digest
SHA256 78ebbd3bdf446952cd927f1afc98dffad54facc590259860903c395e3c2d8357
MD5 5ecc407f6698322fcae67c829d5a9174
BLAKE2b-256 e5c08d55e8baba453812bc136e7ade6aa4f3c1a32f8b54a43aebc3825f502cae

See more details on using hashes here.

File details

Details for the file fastapi_rbac_authz-0.2.0-py3-none-any.whl.

File metadata

  • Download URL: fastapi_rbac_authz-0.2.0-py3-none-any.whl
  • Upload date:
  • Size: 29.7 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/2.3.2 CPython/3.13.2 Darwin/25.2.0

File hashes

Hashes for fastapi_rbac_authz-0.2.0-py3-none-any.whl
Algorithm Hash digest
SHA256 0141e270df2f0c0a20a8037df36008c6a446e18ebfbdde1ed5ded7fe75843a03
MD5 da20ef47e3e49d74c33a3913a1e746d2
BLAKE2b-256 49c453d8648744028c66f9c369bd49934d784d7d6811e9db2217dfd334181c26

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