Appearance
SDK reference
Everything the FastAPI SDK exposes, in one place. The SDK has four classes:
| Class | Use it to | Guide |
|---|---|---|
UserAuth | Sign people in to a web app, with sessions, roles and permissions | FastAPI quickstart |
TokenAuth | Check access tokens, and API keys, on an API | Protect an API |
McpAuth | Protect an MCP server, with scopes per tool | AI and MCP |
MicroAuth | Sell your API with keys, rate limits and usage billing | FastAPI SDK guide |
The SDK needs Python 3.10 or newer. UserAuth, TokenAuth and McpAuth arrived in 3.1.0. PyPI has the latest release, and the changelog lists what changed in each one.
Install
bash
pip install "microauth-fastapi>=3.1"
# With Redis, for limits shared across workers
pip install "microauth-fastapi[redis]>=3.1"
# With the MCP Python SDK, for McpAuth
pip install "microauth-fastapi[mcp]>=3.1"Environment variables
The SDK reads these when the matching constructor argument isn't passed.
| Variable | Used by | Used for |
|---|---|---|
MICROAUTH_ISSUER | UserAuth, TokenAuth, McpAuth, MicroAuthTokenVerifier | Your sign in service, such as https://acme.microauth.dev |
MICROAUTH_CLIENT_ID | UserAuth | The web application's client ID |
MICROAUTH_CLIENT_SECRET | UserAuth | The web application's client secret |
MICROAUTH_COOKIE_SECRET | UserAuth | 32 or more random bytes that encrypt the session cookie. Comma separated to rotate |
MICROAUTH_APP_URL | UserAuth | Your app's public origin, such as https://app.example.com |
MICROAUTH_RESOURCE | TokenAuth, McpAuth, MicroAuthTokenVerifier | The API or MCP server's URL exactly as registered |
MICROAUTH_RESOURCE_CLIENT_ID, MICROAUTH_RESOURCE_SECRET | TokenAuth, McpAuth, MicroAuthTokenVerifier | The server credentials, when they accept API keys |
MICROAUTH_SECRET_KEY | MicroAuth | Your API's SDK secret key (mas_...). Required |
MICROAUTH_BASE_URL | MicroAuth | MicroAuth API base URL. Defaults to https://api.microauth.com |
MICROAUTH_REDIS_URL | MicroAuth, and TokenAuth, McpAuth and MicroAuthTokenVerifier with keys | Optional Redis URL. For MicroAuth: shared limits, snapshots and the durable usage queue. For keys: shared key answers and key limits |
MICROAUTH_JOURNAL_DIR | MicroAuth | Directory for the usage journal. Defaults to a per user state directory, see journal_dir |
The SDK and the check command look for each variable in two places:
- The process environment. A variable set there always wins, even when it is empty.
- A
.envfile in the working directory, the directory the server was started from. OnlyMICROAUTH_*lines are read. Other lines are ignored, and nothing is copied intoos.environ, so you don't need python-dotenv.
The file takes NAME=value lines, optionally starting with export, with # comments and single or double quotes around values. Settings are read when each object is created, so a change to the file needs a restart.
bash
# .env
MICROAUTH_SECRET_KEY=mas_...Pass arguments instead when one app needs two values for the same setting, such as an API and an MCP server that each have their own server credentials.
You see the secret when you launch your API, and you can reveal it again on the Connect tab. Admins can rotate it under Settings, SDK secret key, with a grace period for the old one. Keep secrets on your server, never in a browser or mobile app, and keep .env out of version control.
UserAuth(app=None, **options)
Signs people in to a web app with the OpenID Connect code flow, run from your server, and keeps the session in an encrypted, HttpOnly cookie.
python
from fastapi import Depends, FastAPI
from microauth_fastapi import User, UserAuth
app = FastAPI()
auth = UserAuth(app)
@app.get("/dashboard")
async def dashboard(user: User = Depends(auth.login_required)):
return {"hello": user.name}If you build the app later, create UserAuth() without it and call auth.install(app) before the app starts.
GET /auth/login also takes max_age, such as /auth/login?next=/billing&max_age=600, to make people sign in again unless they did in the last 10 minutes. It goes up to 86400. prompt=login always asks for a fresh sign in, prompt=none only signs in people who already have a MicroAuth session, and login_hint fills in the email address.
Options
| Option | Default | What it does |
|---|---|---|
issuer | MICROAUTH_ISSUER | Your sign in service |
client_id, client_secret | MICROAUTH_CLIENT_ID, MICROAUTH_CLIENT_SECRET | The web application's credentials |
cookie_secret | MICROAUTH_COOKIE_SECRET | 32 or more random bytes. A comma separated string or a list rotates: the first encrypts and all of them decrypt |
app_url | MICROAUTH_APP_URL | Your app's public origin. The redirect URI is this plus prefix plus /callback |
scopes | openid profile email roles | Scopes to ask for. openid is always added. Add offline_access only for refresh tokens that outlive the sign in session |
resource | None | An API to get an access token for, used with keep_access_token |
keep_access_token | False | Keep the access token in the session for await auth.access_token(request). The cookie grows about twice as large |
api_keys | False | Let signed in people manage their own API keys from your app with auth.api_keys. Asks for the microauth:api_keys scope and keeps the access token. Can't be combined with resource |
prefix | /auth | Where the routes live |
after_sign_in | / | Where people land when the sign in link had no next |
after_sign_out | / | Where MicroAuth sends people after sign out. app_url plus this must be a sign out URL of the application |
cookie_name | microauth | Base name of the cookies: __Host-microauth on https |
session_max_age | 30 days | The longest a session lasts, in seconds, however often it's refreshed |
max_age | None | Make people sign in again when their last sign in is older than this many seconds |
leeway | 60 | Seconds of clock skew allowed on token times |
timeout | 10 | HTTP timeout in seconds for calls to MicroAuth |
http_client | None | An httpx.AsyncClient you own |
Routes
| Route | What it does |
|---|---|
GET /auth/login?next=/path | Starts sign in and comes back to next, which must be a path on your site |
GET /auth/signup?next=/path | The same, opening on the sign up screen |
GET /auth/callback | Where MicroAuth sends the browser back after sign in |
POST /auth/logout | Signs out here and at MicroAuth. Send it from a form or fetch on your own site |
GET /auth/me | The signed in user as JSON, or 401 |
Dependencies and methods
| Use | Gives | When nobody qualifies |
|---|---|---|
Depends(auth.user) | User | 401 |
Depends(auth.optional) | User | None | None. A POST, PUT, PATCH or DELETE from another site also gets None, so the route runs as it would for a signed out visitor |
Depends(auth.login_required) | User | Redirects to sign in and back. Use it for pages |
Depends(auth.require(permissions=..., roles=...)) | User | 401 when signed out, 403 without every permission and role listed. Add redirect=True for pages |
auth.user, auth.login_required and auth.require refuse a POST, PUT, PATCH or DELETE from another site with 403.
await auth.access_token(request)returns the signed in user's access token, refreshed when needed. It needskeep_access_token=True. Use it to call an API from your server and never send it to the browser.auth.login_url(next=None, max_age=None)builds the local sign in link, coming back tonext, which must be a path on your site. Withmax_age, from 0 to 86400 seconds, people sign in again unless they did within that time.await auth.login_redirect(request, next=None, prompt=None, login_hint=None, max_age=None)starts a sign in and returns the redirect to MicroAuth, for your own routes. For example,prompt="login"makes someone sign in again before a sensitive action.auth.same_origin(request.headers)is true whenOrigin, orRefererwithout it, is your app's origin.auth.install(app)adds the routes, the session middleware and the error handler when you createdUserAuth()without an app.await auth.aclose()closes the HTTP clientUserAuthmade. Calling it twice is fine.auth.api_keysmanages the signed in person's API keys. See manage keys from your app.
401 and 403 answers are problem JSON (RFC 9457) with the detail field FastAPI clients already read.
Your own refusal pages
To show your own page for a refusal, register an exception handler for that class, before or after UserAuth(app). The SDK never replaces a handler your app registered. await refusal_response(request, exc) builds the answer the SDK would have sent: problem JSON for most refusals and a bare redirect for SignInRedirect. Your handler can still use it for API calls:
python
from fastapi import FastAPI, Request
from fastapi.templating import Jinja2Templates
from microauth_fastapi import PermissionDenied, UserAuth, refusal_response
app = FastAPI()
auth = UserAuth(app)
templates = Jinja2Templates(directory="templates")
@app.exception_handler(PermissionDenied)
async def permission_denied(request: Request, exc: PermissionDenied):
if "text/html" in request.headers.get("accept", ""):
return templates.TemplateResponse(request, "403.html", status_code=403)
return await refusal_response(request, exc)When you build your own response, copy exc.headers onto it, since they carry WWW-Authenticate, Retry-After and Location. The errors table lists every class.
User
| Field | Type | Meaning |
|---|---|---|
id | str | The person's ID on your sign in service. Never changes |
email | str | None | Their email address |
email_verified | bool | Whether they confirmed it |
name | str | None | Their name |
picture | str | None | Their profile photo URL |
roles | frozenset[str] | Their roles, from the roles scope |
permissions | frozenset[str] | Their permissions, from the roles scope |
session_id | str | None | The sign in session |
amr | frozenset[str] | How the person proved who they are at sign in, with RFC 8176 values such as pwd and otp |
auth_time | int | None | When that sign in happened, in Unix seconds |
claims | Mapping | The raw ID token claims |
user.has_role(*names) and user.has_permission(*names) are true when the user holds every name given. Roles and permissions are current as of the last refresh, at most one access token lifetime ago. A refresh changes neither amr nor auth_time, so auth_time tells you how long ago the person last actually signed in. user.to_dict() returns the fields that are safe to send to the browser, everything except claims, as JSON types.
Sessions
- The session cookie is HttpOnly,
SameSite=Lax,Path=/and encrypted with AES-256-GCM. A large session is split into.0,.1and so on, and a cookie that doesn't decrypt counts as signed out. - The SDK refreshes the access token 30 seconds before it expires, once per session even under parallel requests, and writes the new cookie on whatever response your route returns.
- If a refresh fails because MicroAuth can't be reached, the session keeps working for up to 5 minutes past expiry, then routes get
503withRetry-After: 5. If MicroAuth says the session ended, the person is signed out. - POST, PUT, PATCH and DELETE requests that use the session must come from your own origin, checked with
OriginorReferer.
TokenAuth(app=None, **options)
Checks MicroAuth access tokens on an API that other apps call with Authorization: Bearer <token>.
python
from fastapi import Depends, FastAPI
from microauth_fastapi import TokenAuth, TokenClaims
app = FastAPI()
api = TokenAuth(app)
@app.get("/posts")
async def posts(token: TokenClaims = Depends(api.require("posts:read"))):
return {"user": token.sub, "app": token.client_id}Depends(api.require(*scopes)) gives the route TokenClaims when the caller holds every scope listed. With no scopes, it needs only a valid token. TokenAuth(app) adds the metadata route and the problem JSON error handler, and closes the HTTP and Redis clients it made when the app shuts down. If you build the app later, create TokenAuth() without it and call api.install(app) before the app starts.
| Option | Default | What it does |
|---|---|---|
issuer | MICROAUTH_ISSUER | Your sign in service |
resource | MICROAUTH_RESOURCE | This API's URL exactly as registered. Tokens must name it in aud |
scopes | None | Scopes every route needs, on top of each route's own |
scopes_supported | scopes and every scope your routes require | Scopes listed in the protected resource metadata |
api_keys | False | Also accept API keys your users made |
resource_client_id, resource_secret | MICROAUTH_RESOURCE_CLIENT_ID, MICROAUTH_RESOURCE_SECRET | The API's server credentials, for checking keys. Pass both or neither. With api_keys=True, the app won't start without them |
stale_if_error | 600 | Seconds an active key keeps working past its cached answer while MicroAuth can't be reached. 0 turns it off |
unknown_key_limit | 20 | Unknown, revoked or mistyped keys one client address may send per minute. 0 turns the limit off |
client_address | The peer address | A function that takes the request and returns the caller's address. Behind a proxy, read it from a header only your proxy sets |
sessions | None | A UserAuth whose signed in users may call the same routes from the browser. See sessions and keys on one route |
redis_url, redis_client | MICROAUTH_REDIS_URL, None | Share key answers and both key limits between workers. A client you pass is never closed |
leeway | 60 | Seconds of clock skew allowed on exp, nbf and iat |
timeout | 10 | HTTP timeout in seconds for calls to MicroAuth |
jwks_refresh_interval | 900 | Seconds between scheduled refreshes of the signing keys |
http_client | None | An httpx.AsyncClient you own |
- Tokens must be RS256 JWTs of type
at+jwtfrom your issuer, with your resource inaud, unexpired. - Signing keys are refreshed every 15 minutes, and right away, at most once a minute, when a token names a key the SDK hasn't seen.
- A missing or bad token gets
401withWWW-Authenticate: Bearer resource_metadata="...", pluserror="invalid_token"when a token was sent. A token without a required scope gets403witherror="insufficient_scope"and every scope the route needs. - When the issuer can't be reached to check a token, the answer is
503withRetry-After: 5. - The protected resource metadata (RFC 9728) is served at
/.well-known/oauth-protected-resource, followed by the resource's path when it has one:/.well-known/oauth-protected-resource/v1forhttps://api.example.com/v1. Only a resource without a path uses the bare root URL, so several resources on one host each keep their own document.
Methods and properties:
await api.authorize(request, scopes)checks the request's caller againstscopes, afrozenset, and returns itsTokenClaims, or raises the refusal, for code that can't use a dependency. A request with anAuthorizationheader is judged by that header alone.api.metadata()returns the protected resource metadata document, andapi.scopes_supportedthe scopes it lists.api.install(app)adds the metadata route, the error handler and the shutdown cleanup when you createdTokenAuth()without an app.await api.aclose()closes the HTTP and Redis clientsTokenAuthmade and empties its key caches. Calling it twice is fine.
TokenClaims
Who is calling, whether with an access token, an API key or a browser session.
| Field | Type | Meaning |
|---|---|---|
sub | str | The person the caller acts for, in every case |
via | str | "access_token", "api_key", or "session" with the sessions option |
client_id | str | None | The app a token was issued to. None for keys and sessions |
scopes | frozenset[str] | The token's scopes, the key's permissions, or the signed in person's permissions |
issuer | str | Your issuer |
audience | tuple[str, ...] | The token's or key's aud |
expires_at | int | None | Unix time. None for keys that never expire and for sessions |
issued_at | int | Unix time |
token_id | str | None | The token's jti |
session_id | str | None | The sign in session, for tokens tied to one |
auth_time | int | None | When the person last signed in |
key_id | str | None | The key's ID, for keys |
claims | Mapping | Every claim in the token, the introspection answer for a key, or the ID token's claims for a session |
caller.has_scope(*scopes) is true when the caller holds every scope given.
McpAuth(**options)
Checks access tokens and per tool scopes for a Streamable HTTP MCP server built with the official MCP Python SDK, following the MCP 2026-07-28 authorization spec. AI and MCP has a full example.
python
from fastapi import FastAPI
from mcp.server.mcpserver import MCPServer
from microauth_fastapi import McpAuth
mcp = MCPServer("Invoices", log_level="WARNING")
auth = McpAuth(scopes=["invoices:read"])
@mcp.tool()
@auth.tool("invoices:write")
def create_invoice(customer: str, amount_cents: int) -> dict: ...
app = FastAPI()
auth.mount(app, mcp)log_level="WARNING" matters. MCPServer sets Python's root logger to INFO unless told otherwise, and then the MCP SDK and httpx log a line for every request, including the calls McpAuth makes to MicroAuth. The level only applies when the root logger has no handlers yet, so if your app sets up logging itself, do that before creating the MCPServer.
| Option | Default | What it does |
|---|---|---|
issuer | MICROAUTH_ISSUER | Your sign in service |
resource | MICROAUTH_RESOURCE | The MCP server's URL exactly as registered, such as https://app.example.com/mcp |
scopes | None | Scopes every request needs, whatever its JSON-RPC method. The 401 challenge asks clients for these first |
scopes_supported | scopes | Scopes listed in the protected resource metadata |
tool_scopes | None | Scopes per tool name, instead of the decorator |
api_keys | False | Also accept API keys your users made. A key's permissions act as its scopes |
resource_client_id, resource_secret | MICROAUTH_RESOURCE_CLIENT_ID, MICROAUTH_RESOURCE_SECRET | The MCP server's server credentials, for checking keys. Pass both or neither. With api_keys=True, the server won't start without them |
stale_if_error | 600 | Seconds an active key keeps working past its cached answer while MicroAuth can't be reached. 0 turns it off |
unknown_key_limit | 20 | Unknown, revoked or mistyped keys one client address may send per minute. 0 turns the limit off |
client_address | The peer address | A function that takes the request and returns the caller's address |
redis_url, redis_client | MICROAUTH_REDIS_URL, None | Share key answers and both key limits between workers. A client you pass is never closed |
leeway | 60 | Seconds of clock skew allowed on token times |
timeout | 10 | HTTP timeout in seconds for calls to MicroAuth |
jwks_refresh_interval | 900 | Seconds between scheduled refreshes of the signing keys |
max_body_size | 4 MiB | Largest request body accepted, in bytes |
http_client | None | An httpx.AsyncClient you own |
auth.mount(app, server, path=None)serves the MCP server inside your FastAPI or Starlette app, next to its other routes. Call it once, before the app starts. It serves the MCP endpoint atpath, which defaults to the resource's path, or/mcpwhen the resource has none. It also serves the protected resource metadata, starts and stops the MCP server's session manager with your app while your app's own lifespan still runs, and closes the HTTP and Redis clientsMcpAuthmade at shutdown.- An
MCPServerpassed tomountis served statelessly with JSON responses, and the MCP SDK is told to accept only the Host and Origin of your resource URL. Without that, the MCP SDK accepts onlylocalhostand answers421on a real domain. For other transport settings, pass the app instead:auth.mount(app, mcp.streamable_http_app(streamable_http_path="/mcp", ...)), withstreamable_http_pathset to the same path. auth.wrap(mcp.streamable_http_app(...))returns the protected ASGI app, for an MCP server that is the whole site. Serve the result at the root of its host.@auth.tool(*scopes, name=None)declares the scopes a tool needs on top ofscopes, and returns the function unchanged. Stack it under your MCP server's tool decorator. The tool name defaults to the function's name. Tools without declared scopes need onlyscopes, and the SDK logs a warning the first time one is called.auth.scopes_for(tool)returns every scope a call to that tool needs.auth.tool_scopesholds the scopes declared for each tool, not countingscopes, andauth.scopes_supportedthe scopes the metadata lists.auth.metadata()returns the protected resource metadata document.await auth.aclose()closes the HTTP and Redis clientsMcpAuthmade and empties its key caches.mountandwrapcall it at shutdown.current_identity()returns the caller'sTokenClaimsinside a tool. The MCP SDK's ownget_access_token()works too.
How requests are checked:
- Every request, whatever its JSON-RPC method, needs a valid token for the resource holding
scopes. Without a token the client gets401with a challenge that names the metadata URL and those scopes. A token without them gets403. - A
tools/callalso needs the scopes declared for that tool. - A
403names what is missing three ways.WWW-Authenticatehaserror="insufficient_scope", ascopewith every scope the request needs, and anerror_descriptionsuch asThe create_invoice tool needs the invoices:write scope, and this access token doesn't have it. The body is a JSON-RPC error with the same sentence as itsmessage, code403, anderrorandscopeindata. API keys get the same, with "permission" and "API key" in the wording. - When the issuer can't be reached the answer is
503withRetry-After: 5, and a caller over a key limit gets429withRetry-After. - On a POST, a
401,429or503also has a JSON-RPC error body. Itsmessageis theerror_descriptionsentence, itscodeis the HTTP status anddata.erroris the OAuth error code, so MCP clients can show the person why. A401for a request that sent no token at all has nodata, just as itsWWW-Authenticateheader has no error code. GET and DELETE get the plain OAuth error body. Since 3.1.1, one that sent no token gets onlyerror_descriptionthere, with no error code, as a POST does. - Each POST must carry one JSON-RPC message. Batches are refused, and the
Mcp-MethodandMcp-Nameheaders must match the body. - The protected resource metadata is served only at the path inserted URL for the resource,
/.well-known/oauth-protected-resource/mcpforhttps://app.example.com/mcp, and the401challenge points there. Only a resource without a path uses the bare/.well-known/oauth-protected-resource, so an API on the same host keeps its own document.
To run an API and an MCP server in one app, give each its own resource and server credentials as arguments, since the MICROAUTH_RESOURCE* variables hold only one of each:
python
import os
from fastapi import FastAPI
from mcp.server.mcpserver import MCPServer
from microauth_fastapi import McpAuth, TokenAuth
app = FastAPI()
api = TokenAuth(
app,
resource="https://example.com",
api_keys=True,
resource_client_id=os.environ["API_CLIENT_ID"],
resource_secret=os.environ["API_SECRET"],
)
mcp = MCPServer("Tasks", log_level="WARNING")
mcp_auth = McpAuth(
resource="https://example.com/mcp",
scopes=["tasks:read"],
api_keys=True,
resource_client_id=os.environ["MCP_CLIENT_ID"],
resource_secret=os.environ["MCP_SECRET"],
)
mcp_auth.mount(app, mcp)A token or key made for one is refused by the other, and each serves its own metadata: the API at /.well-known/oauth-protected-resource and the MCP server at /.well-known/oauth-protected-resource/mcp. One argument never pairs with the other's environment variable, since that could match one resource's ID with another resource's secret.
MicroAuthTokenVerifier
A TokenVerifier for servers that use the MCP SDK's own auth settings. It checks tokens exactly like TokenAuth:
python
from mcp.server.auth.settings import AuthSettings
from mcp.server.mcpserver import MCPServer
from microauth_fastapi import MicroAuthTokenVerifier
mcp = MCPServer(
"Invoices",
token_verifier=MicroAuthTokenVerifier(),
auth=AuthSettings(
issuer_url="https://acme.microauth.dev",
resource_server_url="https://app.example.com/mcp",
required_scopes=["invoices:read"],
validate_token_resource=True,
),
)Required scopes stay in the MCP SDK's settings, so a missing one is still a 403.
| Option | Default | What it does |
|---|---|---|
issuer | MICROAUTH_ISSUER | Your sign in service |
resource | MICROAUTH_RESOURCE | The MCP server's URL exactly as registered |
api_keys | False | Also accept API keys |
resource_client_id, resource_secret | MICROAUTH_RESOURCE_CLIENT_ID, MICROAUTH_RESOURCE_SECRET | The server credentials, for checking keys |
stale_if_error | 600 | Seconds an active key keeps working past its cached answer while MicroAuth can't be reached |
redis_url, redis_client | MICROAUTH_REDIS_URL, None | Share key answers between workers |
leeway | 60 | Seconds of clock skew allowed on token times |
timeout | 10 | HTTP timeout in seconds for calls to MicroAuth |
jwks_refresh_interval | 900 | Seconds between scheduled refreshes of the signing keys |
http_client | None | An httpx.AsyncClient you own |
The MCP SDK lets a verifier only accept or refuse a token, so some of what McpAuth does isn't possible this way:
- An issuer outage looks like a bad token:
401instead of503withRetry-After. - Per tool scopes aren't checked.
- With
api_keys=True, neither the per person key limit nor the unknown key limit applies, since the verifier never sees the request.
Use McpAuth when you need any of those. await verifier.verify_token(token) returns the MCP SDK's AccessToken for a valid token or key and None otherwise. For a key, that AccessToken gets the key's ID as its client_id. await verifier.aclose() closes the HTTP and Redis clients the verifier made.
API keys for your users
TokenAuth(api_keys=True) and McpAuth(api_keys=True) accept the API keys your users create next to access tokens. Their options are in the TokenAuth and McpAuth tables.
python
from fastapi import Depends, FastAPI
from microauth_fastapi import TokenAuth, TokenClaims
app = FastAPI()
api = TokenAuth(app, api_keys=True)
@app.post("/posts")
async def create_post(caller: TokenClaims = Depends(api.require("posts:write"))):
return {"author": caller.sub, "via": caller.via}bash
MICROAUTH_RESOURCE_CLIENT_ID=...
MICROAUTH_RESOURCE_SECRET=...How a key is checked:
- A bearer value with a dot is a JWT and gets the local access token check. Anything else is treated as a key.
- A value with the wrong shape or checksum gets
401without a call to MicroAuth. - A well formed key is checked with introspection at your issuer, using the server credentials.
- Answers are cached by the key's SHA-256, never the key itself, for as long as MicroAuth's
Cache-Controlallows: 30 seconds today, and never more than 5 minutes. Parallel requests with the same key share one check. - While MicroAuth can't be reached, a key that was active keeps working for
stale_if_errorseconds past its cached answer. A key the SDK hasn't seen before gets503withRetry-After: 5. Errors are never cached. - When MicroAuth refuses the server credentials, callers with keys get
503and the SDK logs an error naming where the credentials came from: the two environment variables, or the arguments. - Raw keys never reach logs, caches or Redis.
For a key, TokenClaims.via is "api_key", sub is the person who made it, scopes are its permissions, key_id identifies it and client_id is None. api.require(...) works the same for keys and tokens.
Limits:
- When the API has "requests per minute for each person's keys" set, the SDK counts it across all of a person's keys at this server. A quiet person can use the whole minute's worth at once, then gets one request every 60 / limit seconds. A caller over it gets
429withRetry-After. Access tokens don't count toward it. - After
unknown_key_limitunknown, revoked or mistyped keys from one client address in a minute, 20 by default, that address gets429withRetry-Afterwithout MicroAuth being asked. - With several workers, set
MICROAUTH_REDIS_URLso every worker shares the cached answers and both limits. If Redis goes down, answers come from MicroAuth instead, but limits can't be checked, so callers with keys get503unless both limits are off.
Sessions and keys on one route
TokenAuth(sessions=auth) lets one route accept a browser signed in with UserAuth along with access tokens and keys:
python
from fastapi import Depends, FastAPI
from microauth_fastapi import TokenAuth, TokenClaims, UserAuth
app = FastAPI()
auth = UserAuth(app)
api = TokenAuth(app, api_keys=True, sessions=auth)
@app.post("/api/posts")
async def create_post(caller: TokenClaims = Depends(api.require("posts:write"))): ...- A request without an
Authorizationheader and with a valid session is a caller withvia="session".subis the user's ID andscopesare their permissions. - A request with an
Authorizationheader is judged by that header alone, even when it also carries the session cookie. - Unsafe requests that use the session must come from your own origin.
- Permissions come with the
rolesscope, soUserAuthmust ask for it, which it does by default, and both must use the same issuer.
Manage keys from your app
With UserAuth(app, api_keys=True), auth.api_keys calls MicroAuth's Account API with the signed in person's access token, so your app can only ever touch that person's keys. Every method takes the request first:
| Method | Returns |
|---|---|
options(request) | APIKeyOptions: max_days, allow_no_expiry, and the resources this person may pick, each with its permissions |
list(request) | A list of APIKey, without secrets |
create(request, name=..., resources=[...], permissions=[...], expires_in_days=...) | NewAPIKey, with key and the secret. Every argument is required. resources are server identifiers and permissions permission names, both from options(). expires_in_days=None asks for a key that never expires |
rename(request, key_id, name) | The renamed APIKey |
roll(request, key_id, old_secret_lasts_hours=0) | NewAPIKey with a new secret. The old one keeps working for 0, 1 or 24 hours |
revoke(request, key_id) | None |
revoke_all(request) | None |
APIKey has id, name, prefix, resources (each with identifier and name), permissions, created_at, created_by_app, expires_at, last_used_at and old_secret_expires_at.
APIKeyOptions.resources is a tuple of APIKeyResourceOption, each with identifier, name and permissions. Each permission is an APIKeyPermission with name, description and sensitive. created_by_app is an APIKeyApp with client_id and name, or None.
python
import html
from fastapi import Depends, FastAPI, Request
from fastapi.responses import HTMLResponse, RedirectResponse
from microauth_fastapi import ReauthenticationRequired, User, UserAuth
app = FastAPI()
auth = UserAuth(app, api_keys=True)
@app.post("/settings/api-keys")
async def create_key(request: Request, user: User = Depends(auth.login_required)):
try:
new = await auth.api_keys.create(
request,
name="CI deploys",
resources=["https://api.example.com"],
permissions=["posts:write"],
expires_in_days=90,
)
except ReauthenticationRequired as exc:
return RedirectResponse(exc.login_url, status_code=303)
return HTMLResponse(
f"<p>Copy your new key now. It won't be shown again.</p><pre>{html.escape(new.secret)}</pre>",
headers={"Cache-Control": "no-store"},
)- The secret is only in
NewAPIKey.secret. Show it right away, send that page withCache-Control: no-store, and never store or log it. - Call the helpers from routes on your own site. Unsafe requests pass the same origin check as everything else that uses the session.
- Only web applications can get
microauth:api_keys, andapi_keys=Truecan't be combined withresource. Sessions from before you turned it on didn't ask for the scope, so the helpers raiseReauthenticationRequiredfor them. - Creating and rolling a key needs a sign in from the last 10 minutes. When it's older, the helper raises
ReauthenticationRequired. Itslogin_urlsigns the person in again and brings them back to the page they were on, andmax_ageis the limit MicroAuth asked for. Left unhandled, it becomes a401problem JSON response that carrieslogin_url. - Nobody signed in, or a session MicroAuth no longer accepts, raises
SignInRequired, and a stale session is cleared. - A refusal, such as an unknown key ID, a name that's too long or a permission the person can't give, raises
AccountAPIErrorwithstatus_code,detail,titleanderrors.detailis one or more full sentences you can show the person as they are. Each item oferrorsis anErrorDetailwithmessage,locationandvalue. - When MicroAuth can't be reached, or fails with a
5xxof its own, the helper raisesAccountAPIUnavailable, a subclass ofAccountAPIErrorwithstatus_code503and thedetail"API keys can't be managed right now. Please try again in a moment." Itsupstream_statusis the status MicroAuth answered, orNonewhen it couldn't be reached, and the SDK logs a warning with the reason. Catch it beforeAccountAPIErrorto treat outages differently. - When MicroAuth won't let this app manage keys at all, the helper raises
MicroAuthConfigurationError.
Errors from UserAuth, TokenAuth and McpAuth
All of these subclass AuthDenied, like the errors below for MicroAuth.
| Exception | Status | Body detail | Raised when |
|---|---|---|---|
SignInRequired | 401 | Sign in to continue | Nobody is signed in, on auth.user and auth.require |
SignInRedirect | 303 | Sign in to continue | Nobody is signed in on a page. Location points to sign in |
PermissionDenied | 403 | You don't have permission to do this | A role or permission is missing. missing_roles and missing_permissions say which |
CrossSiteRequest | 403 | This request came from another site | An unsafe request with the session came from another origin |
InvalidToken | 401 | Says what's wrong | The bearer token is missing, malformed, expired or for another server. Carries WWW-Authenticate |
InsufficientScope | 403 | The access token is missing a scope this request needs | scopes lists every scope the route needs. Carries WWW-Authenticate |
TooManyRequests | 429 | Says which limit | A person's keys went over the API's requests per minute, or one address sent too many unknown keys. Carries Retry-After |
ReauthenticationRequired | 401 | Sign in again to continue | An auth.api_keys call needs a more recent sign in. login_url signs the person in again and max_age is the limit MicroAuth asked for |
AuthUnavailable | 503 | Authorization is temporarily unavailable | A token, key or session can't be checked right now, such as when MicroAuth or Redis can't be reached and nothing usable is cached. Carries Retry-After: 5 |
TooManyRequests subclasses RateLimited. To answer one of these your own way, see your own refusal pages. AccountAPIError and AccountAPIUnavailable come from auth.api_keys. They aren't HTTP errors, so catch them in your route.
MicroAuth(app, secret_key=None, **options)
Sells your API with customer keys, rate limits, quotas and usage billing, and protects internal APIs the same way. It creates the integration and installs a small middleware on app. It records the final status code of every authenticated response, loads the first snapshot when the app starts and drains pending usage when it stops.
python
from fastapi import FastAPI, Security
from microauth_fastapi import Customer, MicroAuth
app = FastAPI()
auth = MicroAuth(app)
@app.get("/forecast")
async def forecast(customer: Customer = Security(auth)):
return {"customer": customer.id}If you build the app later, create MicroAuth() without it and call auth.install(app) before the first request.
Options
All options are keyword arguments with defaults, so pass only what you want to change.
| Option | Default | What it does |
|---|---|---|
secret_key | MICROAUTH_SECRET_KEY | SDK secret key (mas_...) |
base_url | https://api.microauth.com | MicroAuth API base (MICROAUTH_BASE_URL) |
header_name | X-API-Key | Header your customers send their key in |
redis_url | MICROAUTH_REDIS_URL | Shares limits, snapshots and pending usage across processes |
redis_client | None | A redis.asyncio client you own, used instead of redis_url |
redis_max_connections | 64 | Cap for the pool built from redis_url. Requests wait up to one second for a free connection |
shared_snapshot_cache | True | With Redis, share snapshots so cold starts don't all fetch at once |
sync_interval | 30 | Seconds between snapshot refreshes |
report_interval | 5 | Usage is sent when 500 requests are waiting or this many seconds pass |
flush_on_response | Auto | True on Vercel and AWS Lambda. Sends a due batch after each response |
trailing_flush | False | Keeps a serverless invocation alive until the batch deadline so the last burst is reported |
max_snapshot_age | 300 | With fail_open=False, requests get 503 once the snapshot is this old |
max_stale_snapshot_age | 3 × max_snapshot_age | Hard ceiling for serving known keys from stale data |
fail_open | True | Keep serving known keys from a stale snapshot until the hard ceiling |
enforce_balance | True | Return 402 when a paying customer has no credit left |
enforce_quota | True | Return 429 when the monthly quota is used up |
enforce_rps | True | Apply per customer requests a second limits |
enforce_platform_allowance | True | Reserve against your MicroAuth plan's monthly allowance before the handler runs |
verify_negative_ttl | 30 | Seconds an unknown key is remembered as invalid |
timeout | 5 | HTTP timeout in seconds for MicroAuth calls. Each call makes up to three attempts |
http_client | None | An httpx.AsyncClient you own |
journal_dir | MICROAUTH_JOURNAL_DIR | Where queued usage is kept on disk. Defaults to ~/.local/state/microauth/journal on Linux, ~/Library/Application Support/microauth/journal on macOS and %LOCALAPPDATA%\microauth\journal on Windows. Each API gets its own subdirectory |
persist_usage | True | Keep unacknowledged usage across restarts. Turn off only in tests |
max_usage_queue | 10000 | Most reserved and queued usage items at once |
shutdown_timeout | 10 | Seconds allowed for the final usage drain |
on_receipts | None | Called with the receipts of each delivery |
on_rejections | None | Called with the usage MicroAuth refused for good |
Clients you pass in through redis_client or http_client stay yours. The SDK uses them but never closes them.
Dependencies
| Dependency | Resolves to | Use it for |
|---|---|---|
Security(auth) | Customer | Routes that require a valid key |
Security(auth.optional) | Customer | None | Routes that serve anonymous and authenticated callers |
Both add an APIKeyHeader security scheme to your OpenAPI schema, so the Authorize button in Swagger UI works without extra setup.
Customer
The principal your handler receives. It is a frozen dataclass.
| Field | Type | Meaning |
|---|---|---|
id | str | The customer's team ID, a UUID. Stable across keys and teammates |
key_id | str | ID of the API key used for this request |
status | str | Always active inside a handler, because other customers are rejected first |
billing_model | str | payg, subscription or none |
rps | int | Effective requests a second |
price_per_request_micro | int | Effective price per billable request, in micro-USD |
monthly_quota | int | None | Effective monthly request cap, or None for no cap |
credit_balance_micro | int | Estimated prepaid balance after this request's reservation |
platform_monthly_limit | int | None | Your MicroAuth plan's monthly allowance |
platform_monthly_remaining | int | None | Allowance left this month |
platform_monthly_period_end | datetime | None | When the allowance resets |
Money is always an integer in micro-USD: 1,000,000 is one dollar.
Lifecycle
| Method | When to call it |
|---|---|
auth.install(app) | Only if you didn't pass app to the constructor |
await auth.startup() | Loads the first snapshot and starts delivery. The middleware calls it when the app starts, and the first request does when the server skips lifespan events |
await auth.flush_usage() | Delivers everything queued now and waits for MicroAuth's answer, for scripts and tests |
auth.usage_stats() | Returns the process's delivery health |
auth.tenant_id, auth.tenant_name | The API this process serves, once the first snapshot arrived |
await auth.aclose() | During graceful shutdown, so pending usage drains. The installed middleware calls it on app shutdown |
Errors returned to your customers
These come from MicroAuth. Each rejection is a subclass of AuthDenied, which is a FastAPI HTTPException. Register a handler for AuthDenied to change the body.
| Exception | Status | Body detail | Headers |
|---|---|---|---|
InvalidAPIKey | 401 | Invalid or missing API key | WWW-Authenticate: ApiKey header="X-API-Key" |
PaymentRequired | 402 | Insufficient credit balance | |
CustomerSuspended | 403 | This account is suspended | |
CustomerPending | 403 | This account is waiting for approval | |
RateLimited | 429 | Rate limit exceeded | Retry-After |
QuotaExceeded | 429 | Monthly request quota exceeded. It resets on 2026-11-01 at 00:00 UTC | Retry-After, the seconds until the reset |
PlatformAllowanceExceeded | 429 | Platform monthly request allowance exhausted. It resets on 2026-11-01 at 00:00 UTC | Retry-After, the seconds until the reset |
AuthUnavailable | 503 | Authorization is temporarily unavailable |
The two monthly 429s name the start of the next calendar month in UTC, the snapshot's platform_period_end, as the reset time. Version 3.1.0 sent neither the reset time nor Retry-After with them. A paused API is refused with PlatformAllowanceExceeded too, and stays paused after that time until its plan changes.
python
from fastapi import FastAPI
from fastapi.responses import JSONResponse
from microauth_fastapi import AuthDenied, MicroAuth
app = FastAPI()
auth = MicroAuth(app)
@app.exception_handler(AuthDenied)
async def auth_denied(request, exc):
return JSONResponse(
status_code=exc.status_code,
content={"error": exc.detail, "docs": "https://docs.example.com/errors"},
headers=exc.headers or {},
)Problems on your side raise subclasses of MicroAuthError instead. These show up in your logs, not in responses to your customers.
| Exception | Subclass of | Raised when |
|---|---|---|
MicroAuthConfigurationError | MicroAuthError | A setting is missing or invalid, such as a missing secret |
MicroAuthAPIError | MicroAuthError | MicroAuth gave an unexpected answer. Has status_code and detail |
MicroAuthAuthorizationError | MicroAuthAPIError | MicroAuth refused the SDK secret key with 401 or 403 |
AccountAPIError, AccountAPIUnavailable | MicroAuthAPIError | An auth.api_keys call was refused, or MicroAuth couldn't be reached |
MicroAuthResponseError | MicroAuthError | MicroAuth returned malformed or unsafe data |
SnapshotValidationError | MicroAuthResponseError | A snapshot failed validation |
SnapshotCacheError | MicroAuthError | The shared snapshot cache in Redis couldn't be read or updated |
LimitBackendUnavailable | MicroAuthError | A shared limit can't be enforced because Redis is down |
UsageReportingError | MicroAuthError | Base class for usage delivery problems |
UsageQueueFull | UsageReportingError | max_usage_queue is reached. Has max_items |
UsageAcknowledgementError | UsageReportingError | MicroAuth didn't acknowledge every item sent |
UsageStoreError | UsageReportingError | The usage journal or the Redis usage queue couldn't be read or updated |
UsageDrainError | UsageReportingError | Shutdown couldn't deliver everything queued. Has pending_items and detail |
Receipts
on_receipts is called with a list of UsageReceipt after each delivery, before the items leave the queue. A receipt can arrive twice when a process stops between the two steps, so store receipts by idempotency_key. The FastAPI guide shows the hooks in use.
| Field | Type | Meaning |
|---|---|---|
idempotency_key | str | The item's ID, the same on every delivery attempt |
outcome | str | accepted when this delivery recorded the item, duplicate when MicroAuth had recorded it before |
customer_id | str | None | The customer MicroAuth charged |
api_key_id | str | The key the requests used |
usage_policy_id | str | The prices the requests were admitted under |
status_code | int | The response status the item counts |
count | int | Requests in the item. They share a key, policy, status and UTC hour |
period_start | datetime | The UTC hour the requests were served in |
charged_micro | int | None | What MicroAuth charged, in micro-USD |
expected_charge_micro | int | None | What the SDK expected from the prices it enforced. None when this process didn't admit all of the requests |
charge_matches | bool | None | Whether the two agree, when both are known. The SDK logs every mismatch |
recorded_at | datetime | None | When MicroAuth recorded the item |
delivered_at | datetime | When this process received the receipt, on MicroAuth's clock |
Rejections
on_rejections is called with a list of UsageRejection when MicroAuth refuses items for good, for example usage for a key that isn't part of this API. The SDK also refuses usage older than MicroAuth's 45 day limit itself, without sending it. Refused usage is never charged and is kept as a dead letter for the usage command.
| Field | Type | Meaning |
|---|---|---|
idempotency_key | str | The item's ID |
api_key_id, usage_policy_id, status_code, count, period_start | As on a receipt | |
http_status | int | None | The status MicroAuth gave the item, or None when the SDK refused it |
detail | str | Why it was refused |
rejected_at | datetime | When, on MicroAuth's clock |
Hooks can be async. A plain function runs in a worker thread so it can't stall your requests. Each call gets five seconds, and an error or timeout is logged and counted in hook_failures without holding up delivery.
UsageStats
auth.usage_stats() returns the delivery health of the current process. Counters cover the life of the process.
| Field | Meaning |
|---|---|
durability | Where queued usage survives a crash: redis, journal or memory |
journal_dir | This API's journal directory. With Redis, it is the fallback while Redis is unreachable |
queued_items, queued_requests | Usage waiting for delivery |
oldest_queued_at | When the oldest waiting request was queued |
delivered_items, delivered_requests | Usage MicroAuth has recorded, duplicates included |
duplicate_items | Items MicroAuth had already recorded on an earlier attempt |
rejected_items, rejected_requests | Usage MicroAuth refused for good |
charged_micro | The sum of charged_micro over every receipt |
charge_mismatches | Receipts whose charge differed from the expected one |
last_delivery_at | When MicroAuth last acknowledged a delivery |
consecutive_failures | Deliveries that failed in a row. It resets on the next success |
last_error, last_error_at | The latest delivery error |
clock_offset_seconds | Seconds to add to this machine's clock to read MicroAuth's |
hook_failures | Receipt and rejection hook calls that raised or timed out |
Alert on rejected_items and charge_mismatches above zero, on consecutive_failures that keeps growing, and on an oldest_queued_at that keeps getting older.
The check command
check tests an integration end to end without serving traffic or reporting usage. Run it where your API runs, with the same environment:
bash
python -m microauth_fastapi checkIt checks, in order:
- Configuration. The SDK secret key is present and looks like one (
mas_...). - MicroAuth. MicroAuth accepts the secret and returns a snapshot. It prints your API's name and ID, the number of customers and keys, your billable status codes and the allowance used this month. It also measures this machine's clock against MicroAuth's and warns at 2 seconds or more. The SDK uses MicroAuth's time either way, but NTP should be fixed.
- API key. With
--key, it explains how a request with that key would be treated: allowed, or refused with402,403or429and why. - Shared state. With Redis configured, it confirms Redis is reachable and accepts Lua scripts.
- Usage journal. The journal directory is writable and isn't somewhere a reboot clears. It also counts usage still queued there and usage MicroAuth refused.
text
Configuration
ok SDK secret mas_...v6a9
ok MicroAuth API https://api.microauth.com
MicroAuth
ok connected to Weather API (0199d4f2-6c1e-7a3b-9f10-2b6c8d4e5a71)
ok snapshot loaded: 12 customer(s), 19 key(s)
ok clock agrees with MicroAuth within 0.004s
billable status codes: 200, 201, 202, 203, 204, 205, 206
platform allowance: 48,210 of 1,000,000 requests used this month
API key
ok key belongs to customer 01a12b67-8fad-7075-8819-fd5ef0cecc10
plan source: payg, billing: payg
balance: $0.999
price per billable request: $0.001
rate limit: 10 requests per second
ok a request with this key would be allowed
Shared state
ok no Redis configured; each worker enforces limits on its own
Usage journal
ok journal directory is writable (/home/app/.local/state/microauth/journal/5b1e0c7a9d2f4e6b8a3c1d0e)
Everything looks good. Your API is ready to serve keys.The first line of the output names the installed SDK version.
| Flag | Default | Meaning |
|---|---|---|
--key | none | A customer API key (map_...) to evaluate |
--secret-key | MICROAUTH_SECRET_KEY | SDK secret key to test |
--base-url | MICROAUTH_BASE_URL | MicroAuth API URL |
--redis-url | MICROAUTH_REDIS_URL | Redis URL to test |
--journal-dir | MICROAUTH_JOURNAL_DIR | Usage journal directory to test |
--timeout | 10 | HTTP timeout in seconds |
The command exits with 0 when everything passed and 1 when any line reads fail, so it works as a deploy smoke test in CI. On failure it ends with a link to troubleshooting. Settings are read from .env too when they aren't in the environment.
The usage command
usage shows what this host still has to deliver and every item MicroAuth refused, from the journal and, when configured, Redis. It only reads, so it is safe to run next to a live app:
bash
python -m microauth_fastapi usage
python -m microauth_fastapi usage --json # for scripts and alertstext
Weather API (0199d4f2-6c1e-7a3b-9f10-2b6c8d4e5a71)
journal: /home/app/.local/state/microauth/journal/5b1e0c7a9d2f4e6b8a3c1d0e
queued in the journal: 2 item(s) covering 9 request(s), oldest queued 2026-10-11 14:02:17 UTC
usage-c45225c89b50.wal: 2 item(s), last written 2026-10-11 14:02:19 UTC
refused by MicroAuth (journal): 1 item(s)
2026-10-11 13:58:40 UTC HTTP 422 3 request(s) with status 200 in the hour of 2026-10-11 13:00:00 UTC
api_key_id is not a key of this API
item c41d9e7b-2a6f-4b83-9e0c-5f7a1d3b8e62, key 9e7f3a1c-4b2d-4e6f-8a0c-1d3e5f7b9a24Queued usage is delivered by the app itself, so a queue that empties is healthy. One that keeps growing means the app can't reach MicroAuth. Without a secret, or when MicroAuth can't be reached, the command lists every API journal in the directory.
| Flag | Default | Meaning |
|---|---|---|
--json | off | Print JSON instead of text |
--limit | 50 | How many of the newest refused items to list per queue |
--secret-key, --base-url, --redis-url, --journal-dir, --timeout | As for check | Which API, Redis and journal to read |
What the SDK sends
- Every call carries
Authorization: Bearer mas_...and aUser-Agent: microauth-fastapi/<version> python/<version>header. The dashboard shows the SDK version on the Connect tab. - Snapshots are revalidated with
If-None-Match. When nothing changed, MicroAuth answers304 Not Modifiedwith no body. - Usage goes out in batches of up to 500 items to
POST /sdk/v1/usage. Each item names the usage policy its requests were admitted under and keeps the same idempotency key across retries until MicroAuth acknowledges it. MicroAuth answers with a receipt per item.
The endpoints are documented in the HTTP API guide and the API reference.