Skip to content

Authentication & Authorization

FastPluggy ships a minimal auth layer built on Starlette's AuthenticationMiddleware. Auth backends are provided by plugins (e.g. auth_user) and auto-wired at startup.

How it works

  1. No auth plugin installed → all routes are open, request.state.current_user is FPAnonymousUser
  2. Auth plugin installed (e.g. auth_user) → the plugin calls fast_pluggy.set_auth_manager(backend) during on_load_complete, which sets the backend that the always-installed AuthenticationMiddleware delegates to (populating request.user) and flips the auth_enable template global. It does NOT gate anything.

⚠ Installing an auth plugin gates NOTHING by itself. AuthenticationMiddleware identifies the caller; it never rejects one. Every protected surface must opt in with Depends(require_authentication) / require_role(...) — per route or per include_router. An app that loads auth_user and adds no dependency is fully open to anonymous users.

Verifying a gate — test it, don't inspect it

Since FastAPI >= 0.138 include_router(..., dependencies=[...]) no longer bakes the dependencies into the route objects; it wraps them in an _IncludedRouter and resolves them at request time. Walking router.routes / route.dependencies therefore shows the original dependency-free routes and cannot tell you what is gated — an inspection-based test reports "0 routes gated" against a gate that demonstrably works, and would just as happily mis-report a broken one. Assert behaviourally instead:

r = TestClient(app).get("/plugin/thing", follow_redirects=False)
assert r.status_code in (401, 403, 307)   # anonymous is refused

Listing routes with their declared auth

To list what is declared (a debug page, a report), walk the routes with iter_api_routes(..., with_auth=True) from fastpluggy.core.tools.fastapi. It descends into the included routers and yields (full_path, route, requires_auth): the full path with every include prefix, and True when require_authentication is a dependency of the route, of its router, or of an include_router(...) above it. It gives the same answer on FastAPI before and after 0.138. The plugin page's Routes tab, list_router_routes() and inspect_fastapi_route() read it.

from fastpluggy.core.tools.fastapi import iter_api_routes

for path, route, requires_auth in iter_api_routes(app.routes, with_auth=True):
    print(path, sorted(getattr(route, "methods", None) or ["websocket"]), requires_auth)

# A router not mounted yet: pass the dependencies that apply to all of its routes.
iter_api_routes(router.routes, with_auth=True, dependencies=router.dependencies)

Without with_auth it yields (full_path, route) pairs, as before. It reads declarations only: require_authentication reached through another dependency, or require_role(...) alone, is not counted, and a declared gate still says nothing of whether an auth backend is set. Test the behaviour as above when it matters.

You can also pass an auth manager explicitly:

fast_pluggy = FastPluggy(app, auth_manager=my_custom_backend)

If set explicitly, plugins will not override it.

set_auth_manager(backend)

Sets the auth backend at runtime. Called automatically by auth plugins, but can also be used programmatically:

fast_pluggy.set_auth_manager(my_backend)

This: - Sets self.auth_manager - Updates the auth_enable template global

It adds no middleware. AuthenticationMiddleware is installed once, unconditionally, in FastPluggy.__init__, with a DelegatingAuthBackend that re-reads fastpluggy.auth_manager on every request — so set_auth_manager is a plain assignment.

That is load-bearing, not incidental. Starlette freezes app.add_middleware() after the first ASGI call, so the older "add the middleware once the backend arrives" shape could only ever work for a plugin that loaded before the app started serving. Because the middleware is now a fixed point and only the attribute it reads changes, set_auth_manager is safe to call at any time, more than once, and from a degraded-mode self-heal long after the app has been answering requests (fast_pluggy#22).

Dependencies

from fastpluggy.core.auth import require_authentication, require_role

require_authentication

Refuses a caller who is not signed in. What that caller receives is the auth backend's answer (on_authenticate_error): a redirect to its login page, a 401 with its challenge. With no answer it is a plain 401. A caller that asks for JSON is never sent to a login page: see What a refused caller receives. When no auth manager is set, this is a no-op — all requests pass through.

# Protect an entire router
app.include_router(my_router, dependencies=[Depends(require_authentication)])

# Or a single route
@router.get("/secret", dependencies=[Depends(require_authentication)])
async def secret(request: Request): ...

require_role(role: str)

Requires the user to have a specific role (checked against request.auth.scopes). FastPluggy uses "fp_admin" to protect its own admin routes. No-op when auth manager is not set.

app.include_router(admin_router, dependencies=[Depends(require_role("fp_admin"))])

What a refused caller receives

The core answers 401, 403 and 404 with a page, or with JSON when the caller asked for it.

Caller 401 403 404
a browser opening an address, curl, a fetch() that sets no Accept the auth backend's answer (login redirect, challenge), else the 401 page the 403 page the 404 page
a caller whose Accept header prefers application/json 401 {"detail": ...}, with the headers of the refusal (WWW-Authenticate), never a redirect 403 {"detail": ...} 404 {"detail": ...}

detail is the one the route gave to its HTTPException: {"detail": "'fp_admin' role required"}, {"detail": "Task not found"}. It is the body FastAPI itself would send.

Page JavaScript that reads a JSON answer must ask for it, or it receives the page and response.json() throws:

const response = await fetch(url, {method: 'POST', headers: {'Accept': 'application/json'}});
const data = await response.json();          // {"detail": "..."} on a refusal
if (!response.ok) fp.notify(data.detail, 'error');

The test is prefers_json(request) (fastpluggy.core.tools.fastapi): JSON has the higher quality in Accept, or the same quality and a more precise name (application/json, text/plain, */*). */* and no header at all mean the page, as before 0.4.111. A route that serves both a page and data can call it too.

Other statuses (405, 409, 422...) have no core handler: FastAPI answers them in JSON for everybody. The 500 page and the plugin load error page are always pages.

user_has_role(request, role)

The pluggable role-check seam on the auth backend. The menu renderer calls it for every item carrying a required_role; you can call it too for conditional rendering inside a page. Unlike require_role (a hard route guard that raises), this returns a bool and centralises how a role is resolved so you never hardcode a roles-array comparison.

Default policy on AuthInterface:

  1. Super-user is a master key. A user with is_admin, or holding any role in super_user_roles ({"fp_admin", "admin"} by default), passes every check — the admin sees every menu item regardless of required_role.
  2. Otherwise, scope membership: role in request.auth.scopes. Scopes are produced by your authenticate(), so each app already controls how a user's attributes (bool columns, DB roles, LDAP groups…) become roles.
class MyAuth(AuthInterface):
    # Tighten the master key, or set to frozenset() so nobody is a super-user.
    super_user_roles = frozenset({"fp_admin"})

    def user_has_role(self, request, role):
        # Example: role hierarchy — an editor is also a viewer.
        if role == "viewer" and "editor" in request.auth.scopes:
            return True
        return super().user_has_role(request, role)

Override just this one method to get role hierarchies, wildcards, or a permission→role map — no menu or route changes needed.

Current user

Set by CurrentUserMiddleware on every request, from what AuthenticationMiddleware established: when someone is authenticated, request.state.current_user is the same object as request.user, and request.state.roles the same as request.auth. The backend's authenticate() runs once per request.

user = request.state.current_user   # FPAnonymousUser if not authenticated
if user.is_authenticated:
    ...
if user.is_admin:
    ...

Available in templates as {{ request.state.current_user }}.

FPAnonymousUser extends Starlette's UnauthenticatedUser and is used as the fallback when no user is authenticated. It guarantees request.state.current_user is never None.

The user object shape depends on the auth backend. FastPluggy core expects:

Attribute Type Description
is_authenticated bool False for anonymous, True for logged-in users
display_name str Shown in the topbar user menu
is_admin bool Controls visibility of the admin sidebar section
profile_picture str\|None Optional; used for avatar display

Writing a custom auth backend

Implement AuthInterface (extends Starlette's AuthenticationBackend):

from fastpluggy.core.auth.auth_interface import AuthInterface

class MyAuthManager(AuthInterface):
    @property
    def user_model(self):
        return MyUserModel

    async def authenticate(self, conn):
        # Return (AuthCredentials, user) or None. Called once per request (and once
        # per WebSocket connection) with a Starlette HTTPConnection: headers, cookies,
        # client and app are there, the body and the HTTP method are not.
        ...

    async def on_authenticate_error(self, request):
        # What a caller who is not signed in gets. Raise an HTTPException
        # (307 + Location to the login page, 401 + WWW-Authenticate) or return
        # a Response: both stop the request. Return None for a plain 401.
        ...

on_authenticate_error is asked by require_authentication and by the 401 handler, so it can be called twice for one request: keep it free of side effects.

Before 0.4.111 a response RETURNED there did not stop anything: require_authentication handed it back as the dependency's value and the guarded route ran for a caller who was not signed in. A backend that returns its redirect needs FastPluggy>=0.4.111, or must raise it instead.

Then either pass it to FastPluggy(app, auth_manager=MyAuthManager()) or call fast_pluggy.set_auth_manager(MyAuthManager()) from a plugin's on_load_complete.