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 ​