Protect an API
Use this guide when your service is the resource: a REST API, or an MCP server, that receives auth-service access tokens from other clients. (To sign users in to a web app, see FastAPI backend.)
How it works
- Your API has a URL that serves as its audience (RFC 8707 resource identifier), for example
https://api.example.com. auth-service lets an application request tokens for it. - A client obtains an access token whose
audcontains that URL. - Your API verifies the JWT with
BearerVerifier: signature, issuer, audience, expiry and a client binding. It then checks scopes and entitlements. - Unauthenticated clients learn where to sign in from the
WWW-Authenticateheader and the RFC 9728 metadata document, which is how MCP clients discover the authorization server.
Opaque tokens are refused: they carry no audience your API could trust.
A complete FastAPI route
from typing import Literal
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse
from auth_ai import AuthAiError, AuthClient, has_role
from auth_ai.server import (
BearerVerifier,
bearer_challenge,
protected_resource_metadata,
protected_resource_metadata_path,
require_scopes,
)
resource = "https://api.example.com"
# A pure resource server never signs users in, but the configuration still
# requires a client id and a redirect URI.
auth = AuthClient(
{
"issuer": "https://auth.example.com",
"client_id": "my-api",
"redirect_uri": "https://api.example.com/auth/callback",
}
)
verifier = BearerVerifier(auth, audience=resource)
metadata_path = protected_resource_metadata_path(resource)
metadata_url = f"{resource}{metadata_path}"
app = FastAPI()
# RFC 9728: served without authentication.
@app.get(metadata_path)
async def metadata() -> dict[str, object]:
return protected_resource_metadata(
auth,
resource=resource,
scopes_supported=["openid", "profile", "email", "roles", "features"],
)
@app.get("/v1/reports", response_model=None)
async def reports(request: Request) -> dict[str, str] | JSONResponse:
try:
token = await verifier.verify_header(request.headers.get("authorization"))
require_scopes(token, "roles")
if token.user_id is not None and not has_role(token.claims, "analyst"):
return JSONResponse({"error": {"code": "FORBIDDEN"}}, status_code=403)
return {"caller": token.user_id or token.client_id}
except AuthAiError as err:
if err.code not in {"TOK_001", "TOK_003", "TOK_004"}:
raise
error: Literal["invalid_token", "insufficient_scope"] | None
if err.code == "TOK_003":
error = None # no credentials were presented
elif err.code == "TOK_004":
error = "insufficient_scope"
else:
error = "invalid_token"
challenge = bearer_challenge(metadata_url, error=error)
return JSONResponse(
{"error": err.to_public_json()},
status_code=403 if err.code == "TOK_004" else 401,
headers={"www-authenticate": challenge},
)
What you get back
verify and verify_header return a frozen VerifiedAccessToken:
| Field | For a user token | For a client_credentials token |
|---|---|---|
user_id | The user's sub. | None |
client_id | The application the user signed in with (azp). | The calling application. |
scopes | A tuple of the granted scopes. | The granted machine scopes. |
audiences | A tuple of the token's aud values. | Same. |
claims | An AccessTokenClaims, which includes roles, permissions, features, plan, org_id when their scopes were granted. | No user claims. |
Distinguish the two with user_id is None: a machine caller must not be treated as a user.
Which error becomes which answer
AuthAiError | Meaning | Answer |
|---|---|---|
TOK_003 | No Authorization: Bearer header, or a malformed one. | 401, challenge without error (the client has not presented credentials). |
TOK_001 | Bad signature, wrong audience or issuer, expired, opaque token, token not bound to a client. | 401, challenge with error="invalid_token". |
TOK_004 | A required scope is missing (details["missing"]). | 403, challenge with error="insufficient_scope". |
bearer_challenge raises CFG_001 when a value contains ", \, CR or LF, so a header can never be injected through it. Other codes, such as OIDC_001 when the provider cannot be discovered, are not the caller's fault: let them propagate as a server error, as the example does.
Getting a token for your API
- A signed-in user of your web app calls your API with a token minted from their grant: add the API URL to
resourcesin theAuthClientconfiguration, thengrants.get_access_token(sub, resource=...). - Another service uses the
client_credentialsgrant withauth.client_credentials(resource=...); its own application must be allowed to request your URL. It needs aclient_secret. - An MCP client finds the authorization server from your metadata document and runs its own authorization-code flow. The auth-service guide MCP integration covers the provider side.
In every case auth-service rejects a resource it does not know, or that the application is not linked to, with invalid_target.
Other frameworks
Mount the framework-agnostic sign-in handlers in a plain ASGI application, Litestar or Django, with a small bridge between WebRequest, WebResponse and your framework.
Implement the stores
The contracts of SessionStore, GrantStore, GrantLock and ReplayStore, with SQLAlchemy and Redis sketches to adapt to your own database.