Web handlers and ASGI
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.
| Member | Description |
|---|---|
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. |
origin | The origin the SDK builds URLs on: that of redirect_uri, never a request header. |
base_path | The resolved base path. |
Routes
| Route | Method | Behaviour |
|---|---|---|
/login | GET | Sealed 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). |
/callback | GET | Completes 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. |
/me | GET | { "user": SessionUser, "expiresAt": … }, or 401 SES_001. |
/logout | POST | Refused 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-logout | POST | See Server API. Ends every session bound to the logout token's sid. |
/wallet | GET | With the ai option. The wallet account plus topupUrl. |
/wallet/stats | GET | With the ai option. Wallet statistics; query days is an integer from 1 to 90, otherwise 400 REQ_001. |
/models | GET | With 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:
| Status | Codes |
|---|---|
400 | REQ_001, SES_002, OIDC_002 |
401 | SES_001, TOK_001, TOK_002, TOK_003 |
402 | GW_001 |
403 | SES_004, SES_005, TOK_004, GW_003 |
429 | GW_002 |
501 | OIDC_004 |
502 | OIDC_001, OIDC_003, API_001, API_002, GW_005 |
503 | GW_004 |
500 | every 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
| Cookie | Name on HTTPS | Name on loopback HTTP | Lifetime | Content |
|---|---|---|---|---|
| Session | __Host-aai_session | aai_session | session_ttl_seconds | A random 256-bit id, base64url. |
| Sign-in | __Host-aai_login | aai_login | 600 seconds | The 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.
| Type | Members |
|---|---|
WebRequest | method, 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. |
WebResponse | status, 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.
| Export | Description |
|---|---|
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}