Skip to main content

Introduction

casbin-fastapi-decorator is an authorization decorator factory for FastAPI built on top of Casbin.

What is it?

Instead of writing authorization logic as middleware or injecting dependencies into every endpoint signature, this library lets you protect routes with a simple decorator:

@app.get("/articles")
@guard.require_permission("post", "read")
async def list_posts():
...

No middleware registration. No extra parameters in your function signatures. Just a decorator.

Why decorator, not middleware?

Featurecasbin-fastapi-decoratorfastapi-authz / fastapi-casbin-auth
ApproachDecorator per routeGlobal middleware
Per-route permission config
Dynamic objects from requestAccessSubject
No extra params in endpoint signature
Native FastAPI DI integration⚠️ partial
JWT extras
DB-backed policies (SQLAlchemy async)
File policies with hot-reload
Casdoor OAuth2 integration
Works with APIRouter

Middleware-based authorization checks every incoming request globally. With a decorator, you configure permissions exactly where the route is defined — no hidden side effects, no boilerplate dependencies in every function signature.

Core concepts

The library is built around two classes:

  • PermissionGuard — the decorator factory. You create one instance per application (or per module) and use it to decorate routes.
  • AccessSubject — a wrapper for dynamic permission arguments that need to be resolved from the request at runtime.

Optional extras

The core package handles authorization. Four optional extras extend it:

ExtraWhat it adds
fileCachedFileEnforcerProvider for cached file-based policies with hot-reload
jwtJWT token extraction and validation from Bearer headers or cookies
dbDatabaseEnforcerProvider for cached SQLAlchemy-backed policies with hot-reload
casdoorOAuth2 login, cookie-based authentication, and remote policy enforcement via Casdoor

Requirements

  • Python 3.10+
  • FastAPI ≥ 0.115.0
  • Casbin ≥ 1.36.0

Next steps