Guide Home Part 1 - FastAPI Foundations Part 2 - Building Applications Part 3 - Pages and HTML Part 4 - Security and Deployment Part 5 - Going Further Capstone Build Plan Markdown Source All Guides

Chapter 24: Authorization

Authentication answers "who are you?" Authorization answers "what may you do?"

Python patterns:

Resource authorization:

def ensure_can_edit_recipe(user: User, recipe: Recipe) -> None:
    if recipe.owner_id == user.id:
        return
    if "admin" in user.roles:
        return
    raise Forbidden("You cannot edit this recipe")

Keep authorization near the use case. Route-level dependencies are good for broad requirements such as "must be logged in." Resource-specific authorization usually belongs in the service layer after loading the resource.