Chapter 24: Authorization
Authentication answers "who are you?" Authorization answers "what may you do?"
Python patterns:
- Role checks: simple and common.
- Policy functions: close to ASP.NET Core authorization policies.
- Resource-based checks: user may edit this specific recipe if they own it.
- Permission tables: useful for admin-heavy apps.
- External policy engines: useful in larger systems.
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.