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 Fastify 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
createBearerVerifier: 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 Fastify route
import Fastify from "fastify";
import { AuthAiError, createAuthClient, hasRole } from "@circle-rd/auth-ai";
import {
bearerChallenge,
createBearerVerifier,
protectedResourceMetadata,
protectedResourceMetadataPath,
requireScopes,
} from "@circle-rd/auth-ai/server";
const 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.
const auth = createAuthClient({
issuer: "https://auth.example.com",
clientId: "my-api",
redirectUri: "https://api.example.com/auth/callback",
});
const verifier = createBearerVerifier(auth, { audience: resource });
const metadataPath = protectedResourceMetadataPath(resource);
const metadataUrl = `${resource}${metadataPath}`;
const app = Fastify();
// RFC 9728: served without authentication.
app.get(metadataPath, async () =>
protectedResourceMetadata(auth, {
resource,
scopesSupported: ["openid", "profile", "email", "roles", "features"],
}),
);
app.get("/v1/reports", async (request, reply) => {
try {
const token = await verifier.verifyHeader(request.headers.authorization);
requireScopes(token, "roles");
if (token.userId !== null && !hasRole(token.claims, "analyst")) {
return reply.status(403).send({ error: { code: "FORBIDDEN" } });
}
return { caller: token.userId ?? token.clientId };
} catch (err) {
if (!(err instanceof AuthAiError)) throw err;
const insufficient = err.code === "TOK_004";
const challenge = bearerChallenge({
resourceMetadataUrl: metadataUrl,
...(err.code === "TOK_003"
? {}
: { error: insufficient ? "insufficient_scope" : "invalid_token" }),
});
return reply
.status(insufficient ? 403 : 401)
.header("www-authenticate", challenge)
.send({ error: err.toPublicJSON() });
}
});
await app.listen({ host: "0.0.0.0", port: 3000 });
What you get back
verifyHeader returns a VerifiedAccessToken:
| Field | For a user token | For a client_credentials token |
|---|---|---|
userId | The user's sub. | null |
clientId | The application the user signed in with. | The calling application. |
scopes | The granted scopes. | The granted machine scopes. |
claims | Includes roles, permissions, features, plan, org_id when their scopes were granted. | No user claims. |
Distinguish the two with userId === null: a machine caller must not be treated as a user.
Which error becomes which answer
AuthAiError | Meaning | Answer |
|---|---|---|
TOK_003 | No Authorization: Bearer header. | 401, challenge without error (the client has not presented credentials). |
TOK_001 | Bad signature, wrong audience or issuer, expired, opaque token. | 401, challenge with error="invalid_token". |
TOK_004 | A required scope is missing (details.missing). | 403, challenge with error="insufficient_scope". |
bearerChallenge throws CFG_001 when a value contains ", \, CR or LF, so a header can never be injected through it.
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
resourcesincreateAuthClient, thengrants.getAccessToken(sub, { resource }). - Another service uses the
client_credentialsgrant withauth.clientCredentials({ resource }); its own application must be allowed to request your URL. - 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; 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.