Server API
Everything below is exported from auth_ai.server. It needs no web framework.
Bearer verification
BearerVerifier(auth, *, audience) verifies JWT access tokens minted for your API. auth is an AuthClient; audience must be a URL (otherwise CFG_001) and must appear in the token's aud. Opaque tokens are refused.
| Member | Description |
|---|---|
verify(token) -> VerifiedAccessToken | Verifies a raw JWT: signature, issuer, audience and expiry, then that it is bound to a client (azp). Failures are TOK_001. |
verify_header(authorization) -> VerifiedAccessToken | Same, from the value of an Authorization: Bearer … header (str | None). A missing or malformed header raises TOK_003. |
Related functions:
| Function | Description |
|---|---|
extract_bearer_token(authorization) -> str | Returns the token of a bearer Authorization header, or raises TOK_003. |
require_scopes(token, *required) | Raises TOK_004 (with details["missing"]) unless the VerifiedAccessToken carries every listed scope. |
VerifiedAccessToken is a frozen dataclass:
| Field | Description |
|---|---|
user_id | The end user's sub, or None for a client_credentials token (where sub is the client id itself). |
client_id | The OAuth client the token was issued to (azp). |
scopes | tuple[str, ...] of the granted scopes. |
audiences | tuple[str, ...] of the aud values. |
claims | The AccessTokenClaims. |
See Protect an API for a complete example.
Protected-resource metadata
| Function | Description |
|---|---|
protected_resource_metadata(auth, *, resource, scopes_supported=None) -> dict[str, object] | The RFC 9728 document: resource, authorization_servers (the issuer), bearer_methods_supported (["header"]) and, when given, scopes_supported. |
protected_resource_metadata_path(resource) -> str | Where to serve it: /.well-known/oauth-protected-resource followed by the path of resource. |
bearer_challenge(resource_metadata_url, *, error=None, scope=None) -> str | The value of the WWW-Authenticate header of a 401 or 403. error is "invalid_token" or "insufficient_scope". Raises CFG_001 for a value containing ", \, CR or LF. |
Back-channel logout
BackchannelLogoutHandler(*, auth, on_logout, replay_store=None, on_error=None) handles the endpoint auth-service calls when a user signs out. AuthHandlers mounts one at /backchannel-logout for you; build your own only when you do not use the sign-in handlers.
It is a callable: await handler(request) takes a WebRequest and returns a WebResponse. It is called without cookies or credentials, so mount it outside any session or CSRF protection.
| Part | Description |
|---|---|
on_logout | Callable[[BackchannelLogoutEvent], Awaitable[None] | None]. Called with a BackchannelLogoutEvent (sid, sub): end every local session whose stored sid equals this one. |
replay_store | A ReplayStore, defaulting to MemoryReplayStore(). Share it across replicas. |
on_error | Receives every rejected token and failed callback: the response carries no detail. |
Answers:
| Status | When |
|---|---|
204 | The logout token is valid and on_logout succeeded. |
400 with {"error": "invalid_request"} | The content type is not application/x-www-form-urlencoded, the body is larger than 16 KiB, logout_token is missing, or the token is invalid or replayed. |
500 with {"error": "server_error"} | on_logout failed. |
405 with Allow: POST | Any other method. |
verify_logout_token(auth, token, replay_store) -> LogoutTokenClaims is the verifier behind it. It requires a logout+jwt for your client id with the back-channel logout event, a jti, a sid and a sub, no nonce, a lifetime of at most 600 seconds and an iat not in the future, and claims the jti once. Failures are TOK_001. LogoutTokenClaims has sid, sub, jti, iat and exp.
ReplayStore is a protocol with one method, claim(jti, expires_at) -> bool: True the first time, False on a replay. See Implement the stores.
MachineApi
MachineApi(auth) calls the auth-service REST API as your application, with client_credentials tokens minted from its own secret. It raises CFG_001 without a client_secret. The scopes billing:read, consumption:read and consumption:write must be granted to the application by a superadmin; a refused scope raises TOK_004 with details["scope"].
It has two members, billing and consumption. See Billing and consumption.
machine.billing
| Method | Returns | Description |
|---|---|---|
get_subscription(user_id) | SubscriptionView | None | None when the user has no subscription. Fields: plan (id, name), is_active, expires_at, stripe_status, current_period_start, current_period_end, cancel_at_period_end, canceled_at. |
get_usage(user_id) | UsageView | period_start and features: each has feature_key, unit, usage_limit (-1 is unlimited), used and remaining (None when unlimited). |
list_invoices(user_id, *, limit=None, cursor=None) | InvoicePage | items (InvoiceView) and next_cursor. Newest first; limit is 1 to 100. |
An InvoiceView has id, status, billing_reason, currency, amount_due, amount_paid, amount_remaining, period_start, period_end, created_at, hosted_invoice_url and invoice_pdf.
machine.consumption
| Method | Returns | Description |
|---|---|---|
report(user_id, key, value, *, idempotency_key=None) | ConsumptionResult | Reports value units of key. aggregate is the running total (key, total as a decimal string) and metered is True when the key prices a metered feature. |
list_aggregates(user_id) | list[ConsumptionAggregate] | Every running total of a user: key, total and updated_at. |
get_aggregate(user_id, key) | ConsumptionAggregate | One running total. Raises API_001 with details["apiCode"] CONS_003 when the key was never reported. |
report validates before sending and raises CFG_001 for an empty user_id, a key that is not 1 to 64 characters of a-zA-Z0-9., a non-finite or non-numeric value (a bool is refused), or an idempotency_key that is empty or longer than 200 characters once trimmed.
Core API
Reference of the auth_ai module: AuthClient, GrantManager, AiClient, the wallet and gateway clients, claims helpers and errors.
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.