Nâng CaoFastAPI iconFastAPI

FastAPI authorization nên thiết kế theo role hay scope?

Role phù hợp quyền coarse-grained như admin/user/support. Scope phù hợp quyền fine-grained theo action/resource như orders:read, orders:write. OAuth2 scopes tích hợp tốt với OpenAPI và Security dependencies.

Ví dụ dependency kiểm scope:

python
async def require_scope(user: User, scope: str):
    if scope not in user.scopes:
        raise HTTPException(status_code=403, detail="Forbidden")

Production thường kết hợp: role để quản trị đơn giản, scope/permission để kiểm soát API chi tiết.

Authorization phải nằm ở backend, không dựa vào frontend route guard.

Xem toàn bộ FastAPI cùng filter theo level & chủ đề con.

Mở danh sách FastAPI