Skip to main content

Casbin authorization decorator factory for FastAPI

Project description

casbin-fastapi-decorator

Authorization decorator factory for FastAPI based on Casbin and fastapi-decorators.

Decorators are applied to routes — no middleware or dependencies in the endpoint signature.

Installation

pip install casbin-fastapi-decorator

Additional providers:

pip install "casbin-fastapi-decorator[jwt]"   # JWT authentication
pip install "casbin-fastapi-decorator[db]"    # Policies from DB (SQLAlchemy)

Quick start

import casbin
from fastapi import FastAPI, HTTPException
from casbin_fastapi_decorator import AccessSubject, PermissionGuard

# 1. Providers — regular FastAPI dependencies
async def get_current_user() -> dict:
    return {"sub": "alice", "role": "admin"}

async def get_enforcer() -> casbin.Enforcer:
    return casbin.Enforcer("model.conf", "policy.csv")

# 2. Decorator factory
guard = PermissionGuard(
    user_provider=get_current_user,
    enforcer_provider=get_enforcer,
    error_factory=lambda user, *rv: HTTPException(403, "Forbidden"),
)

app = FastAPI()

# 3. Authentication only
@app.get("/me")
@guard.auth_required()
async def me():
    return {"ok": True}

# 4. Static permission check
@app.get("/articles")
@guard.require_permission("articles", "read")
async def list_articles():
    return []

# 5. Dynamic check — value from request
async def get_article(article_id: int) -> dict:
    return {"id": article_id, "owner": "alice"}

@app.get("/articles/{article_id}")
@guard.require_permission(
    AccessSubject(val=get_article, selector=lambda a: a["owner"]),
    "read",
)
async def read_article(article_id: int):
    return {"article_id": article_id}

Arguments of require_permission are passed to enforcer.enforce(user, *args) in the same order. AccessSubject is resolved via FastAPI DI, then transformed by the selector.

API

PermissionGuard

PermissionGuard(
    user_provider=...,       # FastAPI dependency that returns the current user
    enforcer_provider=...,   # FastAPI dependency that returns a casbin.Enforcer
    error_factory=...,       # callable(user, *rvals) -> Exception
)
Method Description
auth_required() Decorator: authentication only (user_provider must not raise an exception)
require_permission(*args) Decorator: permission check via enforcer.enforce(user, *args)

AccessSubject

AccessSubject(
    val=get_item,                        # FastAPI dependency
    selector=lambda item: item["name"],  # transformation before enforce
)

Wraps a dependency whose value needs to be obtained from the request and passed to the enforcer. By default, selector is identity (lambda x: x).

JWT provider

casbin-fastapi-decorator-jwt — extracts and validates a JWT from the Bearer header and/or a cookie.

pip install "casbin-fastapi-decorator[jwt]"

See packages/casbin-fastapi-decorator-jwt/README.md for full API and usage.

DB provider

casbin-fastapi-decorator-db — loads Casbin policies from a SQLAlchemy async session.

pip install "casbin-fastapi-decorator[db]"

See packages/casbin-fastapi-decorator-db/README.md for full API and usage.

Examples

Example Description
examples/core Bearer token auth, file-based Casbin policies
examples/core-jwt JWT auth via JWTUserProvider, file-based policies
examples/core-db Bearer token auth, policies from SQLite via DatabaseEnforcerProvider

Development

Requires Python 3.10+, uv, task.

task install           # uv sync --all-groups + install extras (jwt, db)
task lint              # ruff + ty + bandit for all packages
task tests             # all tests (core + jwt + db)

Individual package tasks:

task core:lint         # lint core only
task core:test         # test core only
task jwt:lint          # lint JWT package
task jwt:test          # test JWT package
task db:lint           # lint DB package
task db:test           # test DB package (requires Docker for testcontainers)

License

MIT

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

casbin_fastapi_decorator-0.1.3.tar.gz (5.1 kB view details)

Uploaded Source

Built Distribution

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

casbin_fastapi_decorator-0.1.3-py3-none-any.whl (6.6 kB view details)

Uploaded Python 3

File details

Details for the file casbin_fastapi_decorator-0.1.3.tar.gz.

File metadata

  • Download URL: casbin_fastapi_decorator-0.1.3.tar.gz
  • Upload date:
  • Size: 5.1 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.10.4 {"installer":{"name":"uv","version":"0.10.4","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

File hashes

Hashes for casbin_fastapi_decorator-0.1.3.tar.gz
Algorithm Hash digest
SHA256 388904a1e32f72e3f2302e02da7d4ae0540f83307bd086e1a764a238a6703f7d
MD5 407eb68cf7a1327cdc4d95d9a4b44f4e
BLAKE2b-256 687307c2cf55e40a605f0acfef28ccd3d8bf132aac24becd1b71a93b0c006a15

See more details on using hashes here.

File details

Details for the file casbin_fastapi_decorator-0.1.3-py3-none-any.whl.

File metadata

  • Download URL: casbin_fastapi_decorator-0.1.3-py3-none-any.whl
  • Upload date:
  • Size: 6.6 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.10.4 {"installer":{"name":"uv","version":"0.10.4","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

File hashes

Hashes for casbin_fastapi_decorator-0.1.3-py3-none-any.whl
Algorithm Hash digest
SHA256 10d80a031b693fa23b22def84ce77f78faad0b5fe765615ca3ec0ebb63474fd9
MD5 7b361ebe40ae5ab271aa16750e43c56b
BLAKE2b-256 e517070c4fab90e46c406dabed319c0bd5b4899c9da470e90521861bdeeddaad

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