Implement fine-grained roles and permissions for FastAPI with Cerbos
FastAPI is a Python-based web framework for building APIs. It’s a preferred framework for developers everywhere, including at tech giants like Microsoft. It is easy to use and has clear documentation.
FastAPI does not have its own recommended framework for access control, so the common solution is to create dependencies and middleware to implement permission checks. It’s relatively easy to do, but the more middleware you have throughout the architecture of your application, the more complicated it gets to maintain. Authorization is one function that tends to create more bloat as your application scales, because it needs to be consistent across all services or else it will be vulnerable to security breaches.
Using a dedicated authorization service like Cerbos will help you keep your code clean, and drastically reduce the complexity involved in authorization maintenance.
Follow these steps to implement Cerbos in your FastAPI application:
Cerbos binaries are available for various different operating systems and architectures. For a list of all available downloads, please visit our releases page on GitHub.
You can install the Cerbos SDK using pip, a package management system written in Python.
Signing up to Cerbos Hub is free and makes it easier to work collaboratively on authorization with teammates and centralize authorization management. When you sign up you will be prompted to create an organization and a workspace, to which you will connect a Github repository.
If you signed up to Cerbos Hub there are built-in tools to help you write and test access control policies. You can also use our Quick Start guide to set up a PDP without Hub. Cerbos policies are written in YAML, and define who is granted access to which resources under which conditions.
The Cerbos configuration file needs to specify the location of your access policy files and other relevant settings that will be necessary to implement your access control protocols. The appropriate file structure is built into Cerbos Hub.
With your policies defined replace the authorization logic in your FastAPI app with a call out to a running Cerbos instance.
The code below demonstrates how to setup the Cerbos SDK and check permissions inside a GET handler.
from fastapi import FastAPI
from cerbos.sdk.model import *
from cerbos.sdk.client import AsyncCerbosClient
app = FastAPI()
@app.get("/expense/{id}")
async def getExpenseById(id):
# Pass the user making the request to Cerbos
principal = Principal(
"john",
roles={"user"},
attr={"department": "marketing", "region": "EMEA"},
)
# Pass the resource to Cerbos
resource = Resource(
"expense1",
"expense",
attr={
"department": "marketing",
"region": "EMEA",
"amount": 10000
"ownerId": "john",
"status": "PENDING",
"createdAt": "2022-08-23T11:30:13.661Z",
},
)
# Connect to the Cerbos PDP
async with AsyncCerbosClient("http://localhost:3592") as c:
# Check access to the resource
allowed = await c.is_allowed("view", p, r)
if allowed:
return {"data": resource}
else:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN, detail="Unauthorized"
)
Cerbos is open source, decoupled access control for your application enabling you to implement fine-grained permissions in minutes.
Define and evolve complex policies without requiring a release cycle
Meet your compliance requirements with a full audit trail of policies, permissions, access to resources
Be enterprise ready and meet your customer's organizational requirements with ease
Coming soon: SIEM integrations and anomaly detection and recommendations of policy changes
Fine grained access controls extending the roles defined in FastAPI
Request time attribute based authorization enables more contextual access controls
Independent authorization logic avoids bloated tokens and workarounds
Define access policies using human-readable YAML. No need to master a new policy language.
Dynamically derive new roles based on contextual information. Don't be limited to what your IdP provides.
Make use of context such as IP address and time of day to make realtime access decisions
Access decisions in milliseconds.
Develop, test, and deploy policies just as you do with your source code.
Built-in policy versioning to support canary deployments and different environments.
Containerised deployment as a microservice or a sidecar. REST and gRPC interfaces. Top-notch observability.
Capture every decision and analyze them later.
Leverage our community for examples and help.
Book a free Policy Workshop to discuss your requirements and get your first policy written by the Cerbos team