CIRCLE
Reference

Web handlers and ASGI

Reference of auth_ai.web and auth_ai.starlette: the routes, the session model, the stores, WebRequest and WebResponse, and the Starlette and FastAPI adapter.

AuthHandlers

auth_ai.web exports AuthHandlers, built synchronously with the options in Configuration. The handlers speak WebRequest and WebResponse, so any framework can mount them: the Starlette and FastAPI adapter is below, the others are in Other frameworks.

MemberDescription
handle(request)Serves the routes below base_path. Returns None for any other path or unknown route, so your application can answer.
get_session(request)The signed-in Session of a request, with claims renewed when due, or None when signed out.
require_session(request)Like get_session, raising SES_001 when signed out.
originThe origin the SDK builds URLs on: that of redirect_uri, never a request header.
base_pathThe resolved base path.

Routes

RouteMethodBehaviour
/loginGETSealed handshake cookie, then 302 to auth-service. Query: next (same-origin path, falls back to default_redirect) and prompt (login, consent, select_account, create or none; anything else is ignored).
/callbackGETCompletes the sign-in, stores the grant, creates the session, then 303 to next with the session cookie. Any failure answers 403 SES_005, or 303 to <error_redirect>?error=SES_005.
/meGET{ "user": SessionUser, "expiresAt": … }, or 401 SES_001.
/logoutPOSTRefused with 403 SES_004 when cross-site. Otherwise ends the current session, revokes the grant if the user has no other session, clears the cookie, then answers { "logoutUrl": … } (Accept: application/json) or 303 to the provider's logout URL (or default_redirect when the provider has no end-session endpoint). Without a session it still answers the provider's logout URL, built without id_token_hint: the provider asks the user to confirm, then ends its single sign-on session for every application. logoutUrl is null only when the provider advertises no end-session endpoint.
/backchannel-logoutPOSTSee Server API. Ends every session bound to the logout token's sid.
/walletGETWith the ai option. The wallet account plus topupUrl.
/wallet/statsGETWith the ai option. Wallet statistics; query days is an integer from 1 to 90, otherwise 400 REQ_001.
/modelsGETWith the ai option. { "models": […] } from the gateway.

A route called with another method answers 405 with Allow. Every JSON response carries Cache-Control: no-store. The JSON uses the camelCase wire names that the TypeScript client reads.

Failure answers

Failures use { "error": { "code", "message" } } with the registry's generic message. Statuses:

StatusCodes
400REQ_001, SES_002, OIDC_002
401SES_001, TOK_001, TOK_002, TOK_003
402GW_001
403SES_004, SES_005, TOK_004, GW_003
429GW_002
501OIDC_004
502OIDC_001, OIDC_003, API_001, API_002, GW_005
503GW_004
500every other code (CFG_001, SES_003, SRV_001)

A failure that is not an AuthAiError, and an AuthAiError answered with a 5xx status (provider or API unreachable, unexpected answer), is passed to on_error; the former is answered 500 SRV_001. The full table with causes and remedies is in Error codes. The table is the STATUS_BY_CODE mapping of auth_ai.web.http, whose error_response(err, on_error) builds such an answer; neither is re-exported from auth_ai.web.

Cookies

CookieName on HTTPSName on loopback HTTPLifetimeContent
Session__Host-aai_sessionaai_sessionsession_ttl_secondsA random 256-bit id, base64url.
Sign-in__Host-aai_loginaai_login600 secondsThe sealed handshake (state, nonce, codeVerifier, next). Cleared after the callback.

Both are Path=/, HttpOnly, SameSite=Lax, plus Secure on HTTPS.

safe_redirect_path(candidate, fallback)

Exported from auth_ai.web. Reduces a redirect target taken from a request to a same-origin path, or returns fallback for None, an absolute URL, a protocol-relative one (//host), a backslash, a control character or anything odd. Use it for your own next parameters.

Session and SessionStore

from dataclasses import dataclass

from auth_ai import IdTokenClaims


@dataclass(frozen=True, slots=True)
class Session:
    id: str  # SHA-256 of the cookie value, base64url
    user_id: str  # the provider's `sub`; also the grant id
    session_id: str | None  # the provider session (`sid`)
    claims: IdTokenClaims
    id_token: str  # hint for the provider's logout endpoint
    created_at: int  # Unix seconds
    expires_at: int  # absolute end of the session
    renew_at: int  # next claims renewal

This is the shape of auth_ai.web.Session, shown for reference: import the real class instead of redefining it.

SessionStore is a protocol with six methods: create, get (None for an unknown or expired session), update, delete, delete_by_provider_session(session_id) (removes and returns every session of a provider session) and count_by_user(user_id). MemorySessionStore is the in-process implementation, for demos and tests. The contracts are detailed in Implement the stores.

create_ai_routes(ai, require_session) builds the /wallet, /wallet/stats and /models handlers that AuthHandlers mounts with the ai option. You normally never call it.

WebRequest and WebResponse

Also exported from auth_ai.web. Both are frozen dataclasses.

TypeMembers
WebRequestmethod, url (absolute; the SDK reads only its path and query), headers (httpx2.Headers), body (bytes). WebRequest.create(method, url, *, headers=None, body=b"") upper-cases the method and takes a mapping or a list of pairs. header(name) returns a value or None.
WebResponsestatus, headers (a tuple of (name, value) pairs, so Set-Cookie can repeat), body (bytes). header(name), header_values(name) and json() read it.

Starlette and FastAPI adapter

auth_ai.starlette needs the starlette or fastapi extra.

ExportDescription
install_auth(app, handlers)Adds a catch-all route below handlers.base_path for GET, POST, PUT, PATCH, DELETE and OPTIONS, and registers an exception handler that answers any AuthAiError with the public envelope. Works on a Starlette or FastAPI application.
require_auth(handlers)Returns a dependency answering 401 SES_001 to signed-out requests and returning the Session otherwise. FastAPI: Depends(require_auth(handlers)). Starlette: call it with the request in your endpoint.
load_session(handlers)Returns a dependency that returns the Session when signed in and None otherwise.
auth_endpoint(handlers)The ASGI endpoint install_auth mounts, if you prefer to add the route yourself.
auth_error_handler(on_error=None)The exception handler install_auth registers, wired to the on_error of your AuthHandlers.
to_web_request(request, origin, *, with_body=False)Builds a WebRequest on origin, not on the Host header. The body is read (capped at 16 KiB) only when asked: the session dependencies leave it to your route.
to_response(response)Converts a WebResponse to a Starlette Response, keeping repeated headers such as Set-Cookie apart.
from typing import Annotated

from fastapi import Depends, FastAPI

from auth_ai.starlette import install_auth, load_session
from auth_ai.web import AuthHandlers, Session

handlers: AuthHandlers  # built as in the FastAPI guide

app = FastAPI()
install_auth(app, handlers)

optional_session = load_session(handlers)


# Optional session: a page that renders for everyone but differently when signed in.
@app.get("/")
async def home(session: Annotated[Session | None, Depends(optional_session)]) -> dict[str, bool]:
    return {"signed_in": session is not None}
Copyright © 2026