Skip to content

SDK reference ​

Everything the FastAPI SDK exposes, in one place. The SDK has four classes:

ClassUse it toGuide
UserAuthSign people in to a web app, with sessions, roles and permissionsFastAPI quickstart
TokenAuthCheck access tokens, and API keys, on an APIProtect an API
McpAuthProtect an MCP server, with scopes per toolAI and MCP
MicroAuthSell your API with keys, rate limits and usage billingFastAPI 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.

VariableUsed byUsed for
MICROAUTH_ISSUERUserAuth, TokenAuth, McpAuth, MicroAuthTokenVerifierYour sign in service, such as https://acme.microauth.dev
MICROAUTH_CLIENT_IDUserAuthThe web application's client ID
MICROAUTH_CLIENT_SECRETUserAuthThe web application's client secret
MICROAUTH_COOKIE_SECRETUserAuth32 or more random bytes that encrypt the session cookie. Comma separated to rotate
MICROAUTH_APP_URLUserAuthYour app's public origin, such as https://app.example.com
MICROAUTH_RESOURCETokenAuth, McpAuth, MicroAuthTokenVerifierThe API or MCP server's URL exactly as registered
MICROAUTH_RESOURCE_CLIENT_ID, MICROAUTH_RESOURCE_SECRETTokenAuth, McpAuth, MicroAuthTokenVerifierThe server credentials, when they accept API keys
MICROAUTH_SECRET_KEYMicroAuthYour API's SDK secret key (mas_...). Required
MICROAUTH_BASE_URLMicroAuthMicroAuth API base URL. Defaults to https://api.microauth.com
MICROAUTH_REDIS_URLMicroAuth, and TokenAuth, McpAuth and MicroAuthTokenVerifier with keysOptional Redis URL. For MicroAuth: shared limits, snapshots and the durable usage queue. For keys: shared key answers and key limits
MICROAUTH_JOURNAL_DIRMicroAuthDirectory 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:

  1. The process environment. A variable set there always wins, even when it is empty.
  2. A .env file in the working directory, the directory the server was started from. Only MICROAUTH_* lines are read. Other lines are ignored, and nothing is copied into os.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 ​

OptionDefaultWhat it does
issuerMICROAUTH_ISSUERYour sign in service
client_id, client_secretMICROAUTH_CLIENT_ID, MICROAUTH_CLIENT_SECRETThe web application's credentials
cookie_secretMICROAUTH_COOKIE_SECRET32 or more random bytes. A comma separated string or a list rotates: the first encrypts and all of them decrypt
app_urlMICROAUTH_APP_URLYour app's public origin. The redirect URI is this plus prefix plus /callback
scopesopenid profile email rolesScopes to ask for. openid is always added. Add offline_access only for refresh tokens that outlive the sign in session
resourceNoneAn API to get an access token for, used with keep_access_token
keep_access_tokenFalseKeep the access token in the session for await auth.access_token(request). The cookie grows about twice as large
api_keysFalseLet 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/authWhere 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_namemicroauthBase name of the cookies: __Host-microauth on https
session_max_age30 daysThe longest a session lasts, in seconds, however often it's refreshed
max_ageNoneMake people sign in again when their last sign in is older than this many seconds
leeway60Seconds of clock skew allowed on token times
timeout10HTTP timeout in seconds for calls to MicroAuth
http_clientNoneAn httpx.AsyncClient you own

Routes ​

RouteWhat it does
GET /auth/login?next=/pathStarts sign in and comes back to next, which must be a path on your site
GET /auth/signup?next=/pathThe same, opening on the sign up screen
GET /auth/callbackWhere MicroAuth sends the browser back after sign in
POST /auth/logoutSigns out here and at MicroAuth. Send it from a form or fetch on your own site
GET /auth/meThe signed in user as JSON, or 401

Dependencies and methods ​

UseGivesWhen nobody qualifies
Depends(auth.user)User401
Depends(auth.optional)User | NoneNone. 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)UserRedirects to sign in and back. Use it for pages
Depends(auth.require(permissions=..., roles=...))User401 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 needs keep_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 to next, which must be a path on your site. With max_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 when Origin, or Referer without it, is your app's origin.
  • auth.install(app) adds the routes, the session middleware and the error handler when you created UserAuth() without an app.
  • await auth.aclose() closes the HTTP client UserAuth made. Calling it twice is fine.
  • auth.api_keys manages 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 ​

FieldTypeMeaning
idstrThe person's ID on your sign in service. Never changes
emailstr | NoneTheir email address
email_verifiedboolWhether they confirmed it
namestr | NoneTheir name
picturestr | NoneTheir profile photo URL
rolesfrozenset[str]Their roles, from the roles scope
permissionsfrozenset[str]Their permissions, from the roles scope
session_idstr | NoneThe sign in session
amrfrozenset[str]How the person proved who they are at sign in, with RFC 8176 values such as pwd and otp
auth_timeint | NoneWhen that sign in happened, in Unix seconds
claimsMappingThe 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, .1 and 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 503 with Retry-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 Origin or Referer.

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.

OptionDefaultWhat it does
issuerMICROAUTH_ISSUERYour sign in service
resourceMICROAUTH_RESOURCEThis API's URL exactly as registered. Tokens must name it in aud
scopesNoneScopes every route needs, on top of each route's own
scopes_supportedscopes and every scope your routes requireScopes listed in the protected resource metadata
api_keysFalseAlso accept API keys your users made
resource_client_id, resource_secretMICROAUTH_RESOURCE_CLIENT_ID, MICROAUTH_RESOURCE_SECRETThe API's server credentials, for checking keys. Pass both or neither. With api_keys=True, the app won't start without them
stale_if_error600Seconds an active key keeps working past its cached answer while MicroAuth can't be reached. 0 turns it off
unknown_key_limit20Unknown, revoked or mistyped keys one client address may send per minute. 0 turns the limit off
client_addressThe peer addressA function that takes the request and returns the caller's address. Behind a proxy, read it from a header only your proxy sets
sessionsNoneA UserAuth whose signed in users may call the same routes from the browser. See sessions and keys on one route
redis_url, redis_clientMICROAUTH_REDIS_URL, NoneShare key answers and both key limits between workers. A client you pass is never closed
leeway60Seconds of clock skew allowed on exp, nbf and iat
timeout10HTTP timeout in seconds for calls to MicroAuth
jwks_refresh_interval900Seconds between scheduled refreshes of the signing keys
http_clientNoneAn httpx.AsyncClient you own
  • Tokens must be RS256 JWTs of type at+jwt from your issuer, with your resource in aud, 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 401 with WWW-Authenticate: Bearer resource_metadata="...", plus error="invalid_token" when a token was sent. A token without a required scope gets 403 with error="insufficient_scope" and every scope the route needs.
  • When the issuer can't be reached to check a token, the answer is 503 with Retry-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/v1 for https://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 against scopes, a frozenset, and returns its TokenClaims, or raises the refusal, for code that can't use a dependency. A request with an Authorization header is judged by that header alone.
  • api.metadata() returns the protected resource metadata document, and api.scopes_supported the scopes it lists.
  • api.install(app) adds the metadata route, the error handler and the shutdown cleanup when you created TokenAuth() without an app.
  • await api.aclose() closes the HTTP and Redis clients TokenAuth made 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.

FieldTypeMeaning
substrThe person the caller acts for, in every case
viastr"access_token", "api_key", or "session" with the sessions option
client_idstr | NoneThe app a token was issued to. None for keys and sessions
scopesfrozenset[str]The token's scopes, the key's permissions, or the signed in person's permissions
issuerstrYour issuer
audiencetuple[str, ...]The token's or key's aud
expires_atint | NoneUnix time. None for keys that never expire and for sessions
issued_atintUnix time
token_idstr | NoneThe token's jti
session_idstr | NoneThe sign in session, for tokens tied to one
auth_timeint | NoneWhen the person last signed in
key_idstr | NoneThe key's ID, for keys
claimsMappingEvery 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.

OptionDefaultWhat it does
issuerMICROAUTH_ISSUERYour sign in service
resourceMICROAUTH_RESOURCEThe MCP server's URL exactly as registered, such as https://app.example.com/mcp
scopesNoneScopes every request needs, whatever its JSON-RPC method. The 401 challenge asks clients for these first
scopes_supportedscopesScopes listed in the protected resource metadata
tool_scopesNoneScopes per tool name, instead of the decorator
api_keysFalseAlso accept API keys your users made. A key's permissions act as its scopes
resource_client_id, resource_secretMICROAUTH_RESOURCE_CLIENT_ID, MICROAUTH_RESOURCE_SECRETThe 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_error600Seconds an active key keeps working past its cached answer while MicroAuth can't be reached. 0 turns it off
unknown_key_limit20Unknown, revoked or mistyped keys one client address may send per minute. 0 turns the limit off
client_addressThe peer addressA function that takes the request and returns the caller's address
redis_url, redis_clientMICROAUTH_REDIS_URL, NoneShare key answers and both key limits between workers. A client you pass is never closed
leeway60Seconds of clock skew allowed on token times
timeout10HTTP timeout in seconds for calls to MicroAuth
jwks_refresh_interval900Seconds between scheduled refreshes of the signing keys
max_body_size4 MiBLargest request body accepted, in bytes
http_clientNoneAn 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 at path, which defaults to the resource's path, or /mcp when 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 clients McpAuth made at shutdown.
  • An MCPServer passed to mount is 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 only localhost and answers 421 on a real domain. For other transport settings, pass the app instead: auth.mount(app, mcp.streamable_http_app(streamable_http_path="/mcp", ...)), with streamable_http_path set 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 of scopes, 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 only scopes, 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_scopes holds the scopes declared for each tool, not counting scopes, and auth.scopes_supported the scopes the metadata lists.
  • auth.metadata() returns the protected resource metadata document.
  • await auth.aclose() closes the HTTP and Redis clients McpAuth made and empties its key caches. mount and wrap call it at shutdown.
  • current_identity() returns the caller's TokenClaims inside a tool. The MCP SDK's own get_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 gets 401 with a challenge that names the metadata URL and those scopes. A token without them gets 403.
  • A tools/call also needs the scopes declared for that tool.
  • A 403 names what is missing three ways. WWW-Authenticate has error="insufficient_scope", a scope with every scope the request needs, and an error_description such as The 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 its message, code 403, and error and scope in data. API keys get the same, with "permission" and "API key" in the wording.
  • When the issuer can't be reached the answer is 503 with Retry-After: 5, and a caller over a key limit gets 429 with Retry-After.
  • On a POST, a 401, 429 or 503 also has a JSON-RPC error body. Its message is the error_description sentence, its code is the HTTP status and data.error is the OAuth error code, so MCP clients can show the person why. A 401 for a request that sent no token at all has no data, just as its WWW-Authenticate header has no error code. GET and DELETE get the plain OAuth error body. Since 3.1.1, one that sent no token gets only error_description there, with no error code, as a POST does.
  • Each POST must carry one JSON-RPC message. Batches are refused, and the Mcp-Method and Mcp-Name headers must match the body.
  • The protected resource metadata is served only at the path inserted URL for the resource, /.well-known/oauth-protected-resource/mcp for https://app.example.com/mcp, and the 401 challenge 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.

OptionDefaultWhat it does
issuerMICROAUTH_ISSUERYour sign in service
resourceMICROAUTH_RESOURCEThe MCP server's URL exactly as registered
api_keysFalseAlso accept API keys
resource_client_id, resource_secretMICROAUTH_RESOURCE_CLIENT_ID, MICROAUTH_RESOURCE_SECRETThe server credentials, for checking keys
stale_if_error600Seconds an active key keeps working past its cached answer while MicroAuth can't be reached
redis_url, redis_clientMICROAUTH_REDIS_URL, NoneShare key answers between workers
leeway60Seconds of clock skew allowed on token times
timeout10HTTP timeout in seconds for calls to MicroAuth
jwks_refresh_interval900Seconds between scheduled refreshes of the signing keys
http_clientNoneAn 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: 401 instead of 503 with Retry-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 401 without 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-Control allows: 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_error seconds past its cached answer. A key the SDK hasn't seen before gets 503 with Retry-After: 5. Errors are never cached.
  • When MicroAuth refuses the server credentials, callers with keys get 503 and 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 429 with Retry-After. Access tokens don't count toward it.
  • After unknown_key_limit unknown, revoked or mistyped keys from one client address in a minute, 20 by default, that address gets 429 with Retry-After without MicroAuth being asked.
  • With several workers, set MICROAUTH_REDIS_URL so 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 get 503 unless 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 Authorization header and with a valid session is a caller with via="session". sub is the user's ID and scopes are their permissions.
  • A request with an Authorization header 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 roles scope, so UserAuth must 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:

MethodReturns
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 with Cache-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, and api_keys=True can't be combined with resource. Sessions from before you turned it on didn't ask for the scope, so the helpers raise ReauthenticationRequired for them.
  • Creating and rolling a key needs a sign in from the last 10 minutes. When it's older, the helper raises ReauthenticationRequired. Its login_url signs the person in again and brings them back to the page they were on, and max_age is the limit MicroAuth asked for. Left unhandled, it becomes a 401 problem JSON response that carries login_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 AccountAPIError with status_code, detail, title and errors. detail is one or more full sentences you can show the person as they are. Each item of errors is an ErrorDetail with message, location and value.
  • When MicroAuth can't be reached, or fails with a 5xx of its own, the helper raises AccountAPIUnavailable, a subclass of AccountAPIError with status_code 503 and the detail "API keys can't be managed right now. Please try again in a moment." Its upstream_status is the status MicroAuth answered, or None when it couldn't be reached, and the SDK logs a warning with the reason. Catch it before AccountAPIError to 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.

ExceptionStatusBody detailRaised when
SignInRequired401Sign in to continueNobody is signed in, on auth.user and auth.require
SignInRedirect303Sign in to continueNobody is signed in on a page. Location points to sign in
PermissionDenied403You don't have permission to do thisA role or permission is missing. missing_roles and missing_permissions say which
CrossSiteRequest403This request came from another siteAn unsafe request with the session came from another origin
InvalidToken401Says what's wrongThe bearer token is missing, malformed, expired or for another server. Carries WWW-Authenticate
InsufficientScope403The access token is missing a scope this request needsscopes lists every scope the route needs. Carries WWW-Authenticate
TooManyRequests429Says which limitA person's keys went over the API's requests per minute, or one address sent too many unknown keys. Carries Retry-After
ReauthenticationRequired401Sign in again to continueAn 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
AuthUnavailable503Authorization is temporarily unavailableA 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.

OptionDefaultWhat it does
secret_keyMICROAUTH_SECRET_KEYSDK secret key (mas_...)
base_urlhttps://api.microauth.comMicroAuth API base (MICROAUTH_BASE_URL)
header_nameX-API-KeyHeader your customers send their key in
redis_urlMICROAUTH_REDIS_URLShares limits, snapshots and pending usage across processes
redis_clientNoneA redis.asyncio client you own, used instead of redis_url
redis_max_connections64Cap for the pool built from redis_url. Requests wait up to one second for a free connection
shared_snapshot_cacheTrueWith Redis, share snapshots so cold starts don't all fetch at once
sync_interval30Seconds between snapshot refreshes
report_interval5Usage is sent when 500 requests are waiting or this many seconds pass
flush_on_responseAutoTrue on Vercel and AWS Lambda. Sends a due batch after each response
trailing_flushFalseKeeps a serverless invocation alive until the batch deadline so the last burst is reported
max_snapshot_age300With fail_open=False, requests get 503 once the snapshot is this old
max_stale_snapshot_age3 × max_snapshot_ageHard ceiling for serving known keys from stale data
fail_openTrueKeep serving known keys from a stale snapshot until the hard ceiling
enforce_balanceTrueReturn 402 when a paying customer has no credit left
enforce_quotaTrueReturn 429 when the monthly quota is used up
enforce_rpsTrueApply per customer requests a second limits
enforce_platform_allowanceTrueReserve against your MicroAuth plan's monthly allowance before the handler runs
verify_negative_ttl30Seconds an unknown key is remembered as invalid
timeout5HTTP timeout in seconds for MicroAuth calls. Each call makes up to three attempts
http_clientNoneAn httpx.AsyncClient you own
journal_dirMICROAUTH_JOURNAL_DIRWhere 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_usageTrueKeep unacknowledged usage across restarts. Turn off only in tests
max_usage_queue10000Most reserved and queued usage items at once
shutdown_timeout10Seconds allowed for the final usage drain
on_receiptsNoneCalled with the receipts of each delivery
on_rejectionsNoneCalled 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 ​

DependencyResolves toUse it for
Security(auth)CustomerRoutes that require a valid key
Security(auth.optional)Customer | NoneRoutes 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.

FieldTypeMeaning
idstrThe customer's team ID, a UUID. Stable across keys and teammates
key_idstrID of the API key used for this request
statusstrAlways active inside a handler, because other customers are rejected first
billing_modelstrpayg, subscription or none
rpsintEffective requests a second
price_per_request_microintEffective price per billable request, in micro-USD
monthly_quotaint | NoneEffective monthly request cap, or None for no cap
credit_balance_microintEstimated prepaid balance after this request's reservation
platform_monthly_limitint | NoneYour MicroAuth plan's monthly allowance
platform_monthly_remainingint | NoneAllowance left this month
platform_monthly_period_enddatetime | NoneWhen the allowance resets

Money is always an integer in micro-USD: 1,000,000 is one dollar.

Lifecycle ​

MethodWhen 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_nameThe 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.

ExceptionStatusBody detailHeaders
InvalidAPIKey401Invalid or missing API keyWWW-Authenticate: ApiKey header="X-API-Key"
PaymentRequired402Insufficient credit balance
CustomerSuspended403This account is suspended
CustomerPending403This account is waiting for approval
RateLimited429Rate limit exceededRetry-After
QuotaExceeded429Monthly request quota exceeded. It resets on 2026-11-01 at 00:00 UTCRetry-After, the seconds until the reset
PlatformAllowanceExceeded429Platform monthly request allowance exhausted. It resets on 2026-11-01 at 00:00 UTCRetry-After, the seconds until the reset
AuthUnavailable503Authorization 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.

ExceptionSubclass ofRaised when
MicroAuthConfigurationErrorMicroAuthErrorA setting is missing or invalid, such as a missing secret
MicroAuthAPIErrorMicroAuthErrorMicroAuth gave an unexpected answer. Has status_code and detail
MicroAuthAuthorizationErrorMicroAuthAPIErrorMicroAuth refused the SDK secret key with 401 or 403
AccountAPIError, AccountAPIUnavailableMicroAuthAPIErrorAn auth.api_keys call was refused, or MicroAuth couldn't be reached
MicroAuthResponseErrorMicroAuthErrorMicroAuth returned malformed or unsafe data
SnapshotValidationErrorMicroAuthResponseErrorA snapshot failed validation
SnapshotCacheErrorMicroAuthErrorThe shared snapshot cache in Redis couldn't be read or updated
LimitBackendUnavailableMicroAuthErrorA shared limit can't be enforced because Redis is down
UsageReportingErrorMicroAuthErrorBase class for usage delivery problems
UsageQueueFullUsageReportingErrormax_usage_queue is reached. Has max_items
UsageAcknowledgementErrorUsageReportingErrorMicroAuth didn't acknowledge every item sent
UsageStoreErrorUsageReportingErrorThe usage journal or the Redis usage queue couldn't be read or updated
UsageDrainErrorUsageReportingErrorShutdown 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.

FieldTypeMeaning
idempotency_keystrThe item's ID, the same on every delivery attempt
outcomestraccepted when this delivery recorded the item, duplicate when MicroAuth had recorded it before
customer_idstr | NoneThe customer MicroAuth charged
api_key_idstrThe key the requests used
usage_policy_idstrThe prices the requests were admitted under
status_codeintThe response status the item counts
countintRequests in the item. They share a key, policy, status and UTC hour
period_startdatetimeThe UTC hour the requests were served in
charged_microint | NoneWhat MicroAuth charged, in micro-USD
expected_charge_microint | NoneWhat the SDK expected from the prices it enforced. None when this process didn't admit all of the requests
charge_matchesbool | NoneWhether the two agree, when both are known. The SDK logs every mismatch
recorded_atdatetime | NoneWhen MicroAuth recorded the item
delivered_atdatetimeWhen 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.

FieldTypeMeaning
idempotency_keystrThe item's ID
api_key_id, usage_policy_id, status_code, count, period_startAs on a receipt
http_statusint | NoneThe status MicroAuth gave the item, or None when the SDK refused it
detailstrWhy it was refused
rejected_atdatetimeWhen, 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.

FieldMeaning
durabilityWhere queued usage survives a crash: redis, journal or memory
journal_dirThis API's journal directory. With Redis, it is the fallback while Redis is unreachable
queued_items, queued_requestsUsage waiting for delivery
oldest_queued_atWhen the oldest waiting request was queued
delivered_items, delivered_requestsUsage MicroAuth has recorded, duplicates included
duplicate_itemsItems MicroAuth had already recorded on an earlier attempt
rejected_items, rejected_requestsUsage MicroAuth refused for good
charged_microThe sum of charged_micro over every receipt
charge_mismatchesReceipts whose charge differed from the expected one
last_delivery_atWhen MicroAuth last acknowledged a delivery
consecutive_failuresDeliveries that failed in a row. It resets on the next success
last_error, last_error_atThe latest delivery error
clock_offset_secondsSeconds to add to this machine's clock to read MicroAuth's
hook_failuresReceipt 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 check

It checks, in order:

  1. Configuration. The SDK secret key is present and looks like one (mas_...).
  2. 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.
  3. API key. With --key, it explains how a request with that key would be treated: allowed, or refused with 402, 403 or 429 and why.
  4. Shared state. With Redis configured, it confirms Redis is reachable and accepts Lua scripts.
  5. 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.

FlagDefaultMeaning
--keynoneA customer API key (map_...) to evaluate
--secret-keyMICROAUTH_SECRET_KEYSDK secret key to test
--base-urlMICROAUTH_BASE_URLMicroAuth API URL
--redis-urlMICROAUTH_REDIS_URLRedis URL to test
--journal-dirMICROAUTH_JOURNAL_DIRUsage journal directory to test
--timeout10HTTP 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 alerts
text
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-1d3e5f7b9a24

Queued 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.

FlagDefaultMeaning
--jsonoffPrint JSON instead of text
--limit50How many of the newest refused items to list per queue
--secret-key, --base-url, --redis-url, --journal-dir, --timeoutAs for checkWhich API, Redis and journal to read

What the SDK sends ​

  • Every call carries Authorization: Bearer mas_... and a User-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 answers 304 Not Modified with 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.

MicroAuth is a product of Zyref, LLC.