Other frameworks
AuthHandlers works on two small framework-agnostic types: handlers.handle(request: WebRequest) resolves to a WebResponse, or to None when the path is not one of its routes. FastAPI and Starlette get a ready-made adapter (FastAPI backend); for anything else you write a thin bridge. There is no Django or Flask adapter in version 0.x.
The types
| Type | Members |
|---|---|
WebRequest | A frozen dataclass: method, url (absolute: the SDK reads only its path and query), headers (an httpx2.Headers) and body (bytes). WebRequest.create(method, url, *, headers=None, body=b"") upper-cases the method and accepts a mapping or a list of pairs for the headers. request.header(name) returns a header value or None. |
WebResponse | A frozen dataclass: status, headers (a tuple of (name, value) pairs, so that Set-Cookie can appear several times) and body (bytes). header(name), header_values(name) and json() read it back. |
Both are exported from auth_ai.web.
The contract your bridge must honour
- Call
handlers.handle(request)for every request belowhandlers.base_path. When it returnsNone, answer404or continue with your own routing. - Build the
WebRequestURL from the registered origin,handlers.origin, followed by the path and query of the incoming request. The SDK does not read theHostheader, and your bridge should not either. - Send every header pair of the response:
Set-Cookieappears more than once on a sign-in, so never collapse the headers into a dictionary. - Give
POST /auth/backchannel-logoutits form body asbytes(application/x-www-form-urlencoded, at most 16 KiB: a larger body is refused with400). Mount it outside any CSRF or session middleware: auth-service calls it with no cookies. - Protect your own routes with
handlers.get_session(request)orhandlers.require_session(request), and answer failures with the public error envelope (err.to_public_json()).
A plain ASGI bridge
ASGI is the common ground of every async Python framework, so one bridge serves them all: it wraps an ASGI application, answers the sign-in routes itself and passes every other request through.
from __future__ import annotations
from collections.abc import Awaitable, Callable, Mapping, MutableMapping
from typing import Any
from auth_ai.web import AuthHandlers, WebRequest, WebResponse
Scope = MutableMapping[str, Any]
Message = MutableMapping[str, Any]
Receive = Callable[[], Awaitable[Message]]
Send = Callable[[Message], Awaitable[None]]
ASGIApp = Callable[..., Awaitable[None]]
MAX_BODY_BYTES = 16_384 # the back-channel logout form is tiny
async def read_body(receive: Receive) -> bytes:
body = b""
while True:
message = await receive()
chunk: bytes = message.get("body", b"")
body += chunk
if len(body) > MAX_BODY_BYTES or not message.get("more_body", False):
return body
def to_web_request(
handlers: AuthHandlers, scope: Mapping[str, Any], body: bytes = b""
) -> WebRequest:
# Built on the registered origin: the Host header is never trusted.
query = scope["query_string"].decode("latin-1")
url = f"{handlers.origin}{scope['path']}" + (f"?{query}" if query else "")
headers = [(k.decode("latin-1"), v.decode("latin-1")) for k, v in scope["headers"]]
return WebRequest.create(scope["method"], url, headers=headers, body=body)
async def send_response(send: Send, response: WebResponse) -> None:
await send(
{
"type": "http.response.start",
"status": response.status,
# One pair per header line: repeated Set-Cookie headers stay apart.
"headers": [(k.encode("latin-1"), v.encode("latin-1")) for k, v in response.headers],
}
)
await send({"type": "http.response.body", "body": response.body})
def with_auth(handlers: AuthHandlers, app: ASGIApp) -> ASGIApp:
"""Serves the sign-in routes of `handlers` and hands every other path to `app`."""
async def middleware(scope: Scope, receive: Receive, send: Send) -> None:
if scope["type"] != "http" or not scope["path"].startswith(f"{handlers.base_path}/"):
await app(scope, receive, send)
return
request = to_web_request(handlers, scope, await read_body(receive))
response = await handlers.handle(request)
await send_response(send, response or WebResponse(404))
return middleware
Here is a bare ASGI application protected with handlers.require_session. auth_ai.web.http.error_response builds the public error envelope with the status the SDK uses for each code (it is a module-level helper, not re-exported from auth_ai.web):
import os
from auth_ai import AuthAiError, AuthClient, GrantManager, MemoryGrantStore
from auth_ai.web import AuthHandlers, MemorySessionStore
from auth_ai.web.http import error_response
from auth_asgi import Receive, Scope, Send, send_response, to_web_request, with_auth
auth = AuthClient(
{
"issuer": os.environ["AUTH_ISSUER"],
"client_id": "my-app",
"client_secret": os.environ["AUTH_CLIENT_SECRET"],
"redirect_uri": "https://app.example.com/auth/callback",
}
)
handlers = AuthHandlers(
auth=auth,
grants=GrantManager(auth=auth, store=MemoryGrantStore()),
sessions=MemorySessionStore(),
secret=os.environ["AUTH_COOKIE_SECRET"],
)
async def api(scope: Scope, receive: Receive, send: Send) -> None:
if scope["type"] != "http":
return
try:
session = await handlers.require_session(to_web_request(handlers, scope))
except AuthAiError as err:
# The public envelope, with the status the SDK itself uses for this code.
await send_response(send, error_response(err, None))
return
body = f'{{"sub": "{session.user_id}"}}'.encode()
await send(
{
"type": "http.response.start",
"status": 200,
"headers": [(b"content-type", b"application/json")],
}
)
await send({"type": "http.response.body", "body": body})
app = with_auth(handlers, api)
Run it with any ASGI server, for example uvicorn asgi_app:app.
Litestar
Wrap the Litestar application and read the session from the request scope in your own handlers:
from typing import Any
from litestar import Litestar, Request, get
from litestar.exceptions import NotAuthorizedException
from auth_ai.web import AuthHandlers
from auth_asgi import to_web_request, with_auth
handlers: AuthHandlers # built as in the previous example
@get("/api/profile")
async def profile(request: Request[Any, Any, Any]) -> dict[str, str]:
session = await handlers.get_session(to_web_request(handlers, request.scope))
if session is None:
raise NotAuthorizedException()
return {"sub": session.user_id}
# `with_auth` wraps the framework's own ASGI application.
app = with_auth(handlers, Litestar([profile]))
Django (ASGI)
Run Django under an ASGI server and wrap its ASGI application in asgi.py. Views are async and read the session from the request scope:
# mysite/asgi.py
import os
from django.core.asgi import get_asgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings")
django_app = get_asgi_application()
from auth_asgi import with_auth # noqa: E402
from mysite.auth import handlers # noqa: E402 (your AuthHandlers)
application = with_auth(handlers, django_app)
# mysite/views.py
from django.core.handlers.asgi import ASGIRequest
from django.http import JsonResponse
from auth_asgi import to_web_request
from mysite.auth import handlers
async def profile(request: ASGIRequest) -> JsonResponse:
session = await handlers.get_session(to_web_request(handlers, request.scope))
if session is None:
return JsonResponse({"error": {"code": "SES_001", "message": "Not signed in"}}, status=401)
return JsonResponse({"sub": session.user_id})
Django's own CSRF middleware does not apply to the sign-in routes, since the wrapper answers them before Django sees the request. Keep it on your own routes.
Flask and other WSGI frameworks
The SDK is async only and AuthClient keeps an httpx2.AsyncClient, so it needs an ASGI server and a running event loop. A synchronous WSGI framework such as Flask cannot host it directly, and there is no sync facade. Use an ASGI framework, or put an ASGI front (like with_auth above) in front of the WSGI application, which needs a WSGI-to-ASGI package that this documentation does not cover.
Stores on serverless platforms
The stores must be shared by every instance (see Implement the stores), which rules out the in-memory stores on serverless platforms.
FastAPI backend
A complete backend-for-frontend on FastAPI: sign-in, sessions, safe logging, same-origin protection, gateway and billing routes.
Protect an API
Verify auth-service bearer tokens on your own API, require scopes, and publish protected-resource metadata so MCP and OAuth clients can find the provider.