An example application of integrating Cerbos with a FastAPI server using SQLAlchemy as the ORM. Cerbos helps you super-charge your authorization implementation by writing context-aware access control policies for your application resources. Author access rules using an intuitive YAML configuration language, use your Git-ops infrastructure to test and deploy them and, make simple API requests to the Cerbos PDP to evaluate the policies and make dynamic access decisions.
- Python >= 3.8
- SQLAlchemy >= 1.4 / 2.0
- Docker for running the Cerbos Policy Decision Point (PDP)
- Start up the Cerbos PDP instance docker container. This will be called by the FastAPI app to check authorization.
cd cerbos
./start.sh
- Install python dependencies
# from project root
pdm install
- Start the FastAPI dev server
pdm run demo
On startup, the app will create an in-memory SQLite instance, and populate it with some sample data - see here.
The following users will be created. Authentication is done via Basic authentication using the provided Usernames (password is omitted). The Role and Department is loaded from the database after successful authentication.
ID | Username | Role | Department |
---|---|---|---|
1 | alice | Admin | IT |
2 | john | User | Sales |
3 | sarah | User | Sales |
4 | geri | User | Marketing |
This example has a simple CRUD policy in place for a resource kind of contact
- like a CRM system would have. The policy files can be found in the cerbos/policies
folder here.
Should you wish to experiment with this policy, you can try it in the Cerbos Playground.
The policy expects one of two roles to be set on the principal - admin
and user
and an attribute which defines their department as either Sales
or Marketing
.
These roles are authorized as follows:
Action | Role: Admin | Derived Role: Owner (User) | Role: User, department: Sales |
Role: User, department: Marketing |
---|---|---|---|---|
read |
Y | Y | if Contact is active | if Contact is active and opted in to marketing |
update |
Y | Y | ||
delete |
Y | Y | ||
create |
Y | Y |
curl -i http://john@localhost:8000/contacts
As a Sales user => 200 OK
curl -i http://john@localhost:8000/contacts/2
As a Marketing user => 403 Unauthorized
curl -i http://geri@localhost:8000/contacts/2