Scoped Permissions: Quick Start
This guide takes you from nothing to a FastAPI route that only a project editor may call. It uses
the in-memory store first and then shows how to switch to PostgreSQL, MySQL or DynamoDB. A complete runnable
version of the first part is examples/authz_example.py (tested in the suite).
1. Install only what you need
pip install auth-middleware # core + scoped permissions, no database driver
pip install 'auth-middleware[postgres]' # + SQLAlchemy, asyncpg (SQL store)
pip install 'auth-middleware[mysql]' # + SQLAlchemy, aiomysql (SQL store)
pip install 'auth-middleware[sqlalchemy]' # both SQL drivers (historical name)
pip install 'auth-middleware[dynamodb]' # + PynamoDB (DynamoDB store)
The scoped-permissions code itself (catalog, guard, in-memory store) is in the core package. A store whose
extra is missing raises an ImportError that names the extra to install.
2. Describe your permissions (the catalog)
Decide what a scope is (a tenant, a project, a studio…), which permissions exist inside it and which roles bundle them. The catalog is validated when built and never changes afterwards.
catalog = PermissionCatalog.from_mapping(
scopes=[ScopeKind("project")],
permissions=[
PermissionSpec("docs.read", "project"),
PermissionSpec("docs.write", "project"),
],
roles={"EDITOR": ["docs.read", "docs.write"], "VIEWER": ["docs.read"]},
)
The same catalog can live in a TOML or JSON file (PermissionCatalog.from_file), see The Permission Catalog.
3. Choose a store and build Authz
The store holds who has which role in which scope. Pick one (all pass the same contract test suite):
def memory_authz() -> Authz:
"""Tests and demos: nothing to install."""
return Authz.build(catalog=catalog, store=InMemoryAssignmentStore())
def sql_authz(database_url: str) -> Authz:
"""SQL (pip install 'auth-middleware[postgres]' or '[mysql]').
``database_url`` e.g. ``postgresql+asyncpg://user:pw@host/db`` or
``mysql+aiomysql://user:pw@host/db``. Create the table with the Alembic
revision shipped in ``alembic/`` or with ``sql_models.metadata``.
"""
from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine
from auth_middleware.authz.stores import SqlAssignmentStore
engine = create_async_engine(database_url, pool_pre_ping=True)
sessions = async_sessionmaker(engine, expire_on_commit=False)
return Authz.build(catalog=catalog, store=SqlAssignmentStore(sessions))
def dynamodb_authz(table_name: str, **options: Any) -> Authz:
"""DynamoDB (pip install 'auth-middleware[dynamodb]').
The table must exist: ``DynamoDbAssignmentStore.table_definition(name)``
returns the ``create_table`` arguments. Credentials come from the usual
AWS chain; ``region`` and ``endpoint_url`` are optional keyword options.
"""
from auth_middleware.authz.stores import DynamoDbAssignmentStore
store = DynamoDbAssignmentStore(table_name=table_name, **options)
return Authz.build(catalog=catalog, store=store)
The SQL table comes from the Alembic revision a3f1c9d2b7e4 (or from
auth_middleware.authz.stores.sql_models.metadata in your own migrations). The DynamoDB table comes from
DynamoDbAssignmentStore.table_definition(name) (see DynamoDB Setup for Scoped Permissions). Nothing in the
library reads environment variables to choose a backend: you inject it here.
To share the request’s own database session (one transaction per request, row-level security) use a per-request store instead:
def sql_per_request_authz() -> Authz:
"""SQL sharing the request's own session (one transaction per request)."""
from auth_middleware.authz.stores import SqlAssignmentStore
def store_for(request: Request) -> SqlAssignmentStore:
# `request.state.session` is an AsyncSession opened by your own dependency,
# which FastAPI must run *before* the permission guard.
return SqlAssignmentStore(request.state.session)
return Authz.build(catalog=catalog, store_factory=store_for)
4. Install it on the application and guard routes
app = FastAPI(on_startup=[seed])
app.add_middleware(DemoAuth)
Authz.build(
catalog=catalog,
store=store,
group_roles={"platform-admins": "PLATFORM_ADMIN"}, # token group -> global role
).install(app)
install also checks at startup that every guarded route uses a permission that exists in the catalog.
Then protect a route; the scope comes from a path parameter:
@app.put("/studios/{studio_id}/design", openapi_extra=permission_extra("design.write"))
async def write_design(
studio_id: str,
ctx: AuthzContext = Depends(require_permission("design.write", scope=studio)),
) -> dict[str, bool]:
return {"saved": True}
Authentication still comes from JwtAuthMiddleware (see User Guide): the guard reads
request.state.current_user and uses its id (the token sub) as the principal.
What callers get:
401: no authenticated user.404: the user has no active assignment in that scope, or the scope does not exist (the two are indistinguishable on purpose).403with{"detail": {"error": "forbidden", "required_permission": "..."}}: the user belongs to the scope but lacks the permission.
5. Give people roles
Your application decides who may be assigned what (invitations, “last owner” rules…). Use
AssignmentService from your own endpoints, or the CLI for operations:
from auth_middleware.authz import AssignmentService, ScopeRef
service = AssignmentService(store, catalog) # store: any store with the write side
scope = ScopeRef("project", "p-1")
assignment = await service.assign("user-sub", scope, "EDITOR")
await service.change_role("user-sub", scope, "VIEWER", expected_revision=assignment.revision)
await service.revoke("user-sub", scope, expected_revision=assignment.revision + 1)
export AUTHZ_SQLALCHEMY_DATABASE_URI=postgresql+asyncpg://user:pw@host/db # or AUTHZ_DYNAMODB_TABLE
authcli authz assign --store sqlalchemy --principal user-sub --scope project:p-1 --role EDITOR
authcli authz list --store sqlalchemy --scope project:p-1
Revisions make concurrent edits safe: a stale expected_revision raises RevisionConflictError.
Platform-wide staff can be derived from token groups instead of stored assignments:
Authz.build(..., group_roles={"staff": "PLATFORM_ADMIN"}).
6. Test your routes
Use the in-memory store and drive the app with httpx exactly as tests/authz/test_example.py does. Add an
architecture test that no route is left unguarded with declared_permissions(app) (see FastAPI Integration).
Where next
Concepts and the 404/403 rule: Scoped Permissions: Overview
Stores, contract tests, own adapters: Assignment Stores
Error policy, OpenAPI, mounted apps: FastAPI Integration
Operations (cache, audit, metrics): Operations: Service, CLI, Cache, Audit