FastAPI
FastAPI

Authorization for FastAPI applications with Cerbos

Implement fine-grained roles and permissions for FastAPI with Cerbos

Building fine-grained access control for a FastAPI app

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.



Advantages of using Cerbos for FastAPI roles and permissions

  1. Low latency
    If fast performance is a major reason you chose FastAPI for your application, rest assured Cerbos can match your requirements. Cerbos evaluates access requests for dynamic policies based on real-time conditions in sub-milliseconds. 
  2. Fine-grained policies
    Configure ABAC, RBAC, row-level, and context-aware access policies. And enforce access control at the API level by integrating Cerbos, thereby providing greater security for key resources.
  3. Cross-service and multi-tenant compatibility
    Both Cerbos and FastAPI are well-suited for distributed or stratified architectures. When you integrate Cerbos with FastAPI you ensure consistent access control between microservices, and customizable to different tenants’ specific requirements.
  4. Transparency and control
    When you integrate Cerbos with FastAPI you can track access to control decisions, audit access requests, investigate security incidents and enhance compliance with GDPR and other regulations.

How to integrate Cerbos with a FastAPI server


authorization for FastAPI applications

Follow these steps to implement Cerbos in your FastAPI application:

Step 1: Install the Cerbos authorization service

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.


Step 2: Install the Cerbos SDK for Python

You can install the Cerbos SDK using pip, a package management system written in Python.


Step 3: Sign in to Cerbos Hub (optional)

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.


Step 4: Build roles and permission

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.


Step 5: Create a configuration file for Cerbos

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.

Step 6: Integrate Cerbos with FastAPI

With your policies defined replace the authorization logic in your FastAPI app with a call out to a running Cerbos instance.


Cerbos and FastAPI Code Example

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"
      )


What is Cerbos?

Cerbos is open source, decoupled access control for your application enabling you to implement fine-grained permissions in minutes.

Agile

Define and evolve complex policies without requiring a release cycle

Compliance

Meet your compliance requirements with a full audit trail of policies, permissions, access to resources

Enterprise

Be enterprise ready and meet your customer's organizational requirements with ease

Proactive

Coming soon: SIEM integrations and anomaly detection and recommendations of policy changes

image

Extend FastAPI Roles

Fine grained access controls extending the roles defined in FastAPI

image

Enrich with Context

Request time attribute based authorization enables more contextual access controls

image

Avoid Token Bloat

Independent authorization logic avoids bloated tokens and workarounds

Why Cerbos?

image

Simple

Define access policies using human-readable YAML. No need to master a new policy language.

image

Super-charged Roles

Dynamically derive new roles based on contextual information. Don't be limited to what your IdP provides.

image

Context-aware

Make use of context such as IP address and time of day to make realtime access decisions

image

Ultrafast API

Access decisions in milliseconds.

image

GitOps

Develop, test, and deploy policies just as you do with your source code.

image

Multiple Environments

Built-in policy versioning to support canary deployments and different environments.

image

Cloud Native

Containerised deployment as a microservice or a sidecar. REST and gRPC interfaces. Top-notch observability.

image

Audit Logs

Capture every decision and analyze them later.

image

Community

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