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.