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 not middleware?

ApproachHow it worksDrawback
MiddlewareIntercepts all requests, checks URL pathHard to do per-route logic
Dependency injectionAdd Depends(...) to every endpointClutters function signatures
Decorator (this library)Decorates the route function directlyClean, explicit, per-route

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. Three optional extras extend it:

ExtraWhat it adds
jwtJWT token extraction and validation from Bearer headers or cookies
dbLoading Casbin policies from a SQLAlchemy async database
casdoorOAuth2 authentication via Casdoor with remote policy enforcement

Requirements

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

Next steps