RBAC in Python with FastAPI
This tutorial adds role-based access control (RBAC) to a REST API built with FastAPI and PyCasbin. At the end, three roles (admin, editor, viewer) are allowed different HTTP methods on different routes, and the rules live in a policy file that you can change without touching the route functions.
The same model and policy work in every Casbin implementation, so you can reuse them in the Go, Node.js, and Java versions of this tutorial.
1. Install
pip install casbin fastapi uvicorn
2. Write the model
The model says what a request looks like and how it is matched against the policy. Save this as model.conf:
[request_definition]
r = sub, obj, act
[policy_definition]
p = sub, obj, act
[role_definition]
g = _, _
[policy_effect]
e = some(where (p.eft == allow))
[matchers]
m = g(r.sub, p.sub) && keyMatch2(r.obj, p.obj) && regexMatch(r.act, p.act)
r = sub, obj, act: each request is a user, a URL path, and an HTTP method.g = _, _: users can be assigned to roles.g(r.sub, p.sub): the request's user must have the role named in the policy rule.keyMatch2matches paths such as/api/articles/:id, andregexMatchlets one rule list several methods. See Functions for the other built-in matchers.