Role-Based Access Control (RBAC)

Role-Based Access Control (RBAC)

Master authorization. Learn how to design a permissions system that restricts specific endpoints to Admins, Managers, or regular Users.

Role-Based Access Control (RBAC)

Authentication says "You are authenticated." Authorization (RBAC) says "You are authenticated, but you aren't an Admin, so you can't delete this database."

In a production application, you have different personas. In this lesson, we learn to implement a clean, scalable permissions system using FastAPI's dependency injection.


1. Defining Roles

The simplest way is to add a role field to your User model (usually an Enum).

from enum import Enum

class Role(str, Enum):
    ADMIN = "admin"
    MANAGER = "manager"
    USER = "user"

2. The Permission Dependency

We can create a dependency that requires a specific role.

class RoleChecker:
    def __init__(self, allowed_roles: List[Role]):
        self.allowed_roles = allowed_roles

    def __call__(self, user: User = Depends(get_current_user)):
        if user.role not in self.allowed_roles:
            raise HTTPException(
                status_code=403, 
                detail="Operation not permitted"
            )
        return user

3. Applying RBAC to Endpoints

Now, you can protect any endpoint by simply adding your RoleChecker as a dependency.

allow_admins = RoleChecker([Role.ADMIN])
allow_managers = RoleChecker([Role.ADMIN, Role.MANAGER])

@app.delete("/system-reset", dependencies=[Depends(allow_admins)])
def reset_system():
    return {"status": "Complete"}

@app.get("/analytics", dependencies=[Depends(allow_managers)])
def get_reports():
    return {"data": "Secret business info"}

4. Scopes (Advanced OAuth2)

If you are building a public-facing API (like GitHub or Spotify), you might use Scopes instead of Roles. Scopes describe "What the app is allowed to do" (e.g., read:users, write:posts) rather than "Who the user is."

FastAPI has built-in support for Scopes via SecurityScopes.


Visualizing the RBAC Matrix

EndpointStandard UserManagerAdmin
GET /profile
PATCH /settings
GET /analytics
DELETE /user

Summary

  • RBAC is the second layer of security (Authorization).
  • Class-Based Dependencies: Use them to create configurable role checks.
  • Enum: Use it to prevent "Magic String" errors in your role logic.
  • 403 Forbidden: Always use this status code when the user is known but lacks permissions.

In the next lesson, we wrap up Module 9 with Exercises on securing your FastAPI application.


Exercise: The Promotion

You want to create an endpoint @app.post("/promote") that allows an Admin to change a regular User's role to Manager.

  1. Which RoleChecker would you apply to this endpoint?
  2. Why is it important to perform this check on the Server and not just hide the button on the Frontend?

Subscribe to our newsletter

Get the latest posts delivered right to your inbox.

Subscribe on LinkedIn