CIRCLE
Backend

Protect an API

Verify auth-service bearer tokens on your own API, require scopes, and publish protected-resource metadata so MCP and OAuth clients can find the provider.

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

  1. 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.
  2. A client obtains an access token whose aud contains that URL.
  3. Your API verifies the JWT with BearerVerifier: signature, issuer, audience, expiry and a client binding. It then checks scopes and entitlements.
  4. Unauthenticated clients learn where to sign in from the WWW-Authenticate header 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:

FieldFor a user tokenFor a client_credentials token
user_idThe user's sub.None
client_idThe application the user signed in with (azp).The calling application.
scopesA tuple of the granted scopes.The granted machine scopes.
audiencesA tuple of the token's aud values.Same.
claimsAn 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

AuthAiErrorMeaningAnswer
TOK_003No Authorization: Bearer header, or a malformed one.401, challenge without error (the client has not presented credentials).
TOK_001Bad signature, wrong audience or issuer, expired, opaque token, token not bound to a client.401, challenge with error="invalid_token".
TOK_004A 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 resources in the AuthClient configuration, then grants.get_access_token(sub, resource=...).
  • Another service uses the client_credentials grant with auth.client_credentials(resource=...); its own application must be allowed to request your URL. It needs a client_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.

Verification fetches the provider's signing keys once and caches them (for an hour at most); an unknown key id triggers at most one reload every 30 seconds, so key rotation is picked up without a restart and a flood of forged tokens cannot hammer the provider.
Copyright © 2026