Skip to Content

Protect your API

Verify provider-issued access tokens in your API or another service.

A resource server is the API that receives access tokens from your OAuth clients.

Verify access tokens

To verify access tokens, call verifyAccessTokenRequest from @entro314labs/entro-auth/oauth2 on each request. It verifies the token and, when the token is DPoP-bound, also checks the proof against the request method and URL (RFC 9449 §7).

api/posts.ts
import { createResourceServerChallenge } from "@entro314labs/entro-auth-oauth-provider";
import { isAPIError } from "@entro314labs/entro-auth/api";
import {
  requestToResourceInput,
  verifyAccessTokenRequest,
} from "@entro314labs/entro-auth/oauth2";

export const GET = async (req: Request) => {
  try {
    const payload = await verifyAccessTokenRequest(requestToResourceInput(req), {
      jwksUrl: "https://auth.example.com/api/auth/jwks",
      verifyOptions: {
        issuer: "https://auth.example.com/api/auth",
        audience: "https://api.example.com",
        typ: "at+jwt",
        requiredClaims: ["azp"],
      },
      requiredScopes: ["read:post"],
    });
    return Response.json({ sub: payload.sub });
  } catch (error) {
    if (!isAPIError(error)) throw error;
    const challenge = createResourceServerChallenge(error, "https://api.example.com", {
      request: req,
    });
    return Response.json(error.body, {
      status: error.statusCode,
      headers: challenge?.headers,
    });
  }
};

typ: "at+jwt" and requiredClaims: ["azp"] reject any JWT that is not an OAuth access token. The provider sets both on every JWT access token (RFC 9068 §2.1). Without them, a JWT plugin session JWT signed with the same key passes whenever its iss and aud match. That token was issued to a signed-in user, not to an OAuth client, and carries no consent or scopes.

requestToResourceInput reads the Authorization and DPoP headers, the method, and the URL from a standard Request. If your framework has no Request, pass { authorizationHeader, dpopProofJwt, method, url } instead. When the token lacks a required scope, the call throws a 403 insufficient_scope error. Its body.scope lists every missing scope (RFC 6750 §3.1), so the client knows which scopes to request when it authorizes again. Catch the thrown APIError and return its statusCode, as above. Most frameworks turn an uncaught error into a 500.

The thrown error has no WWW-Authenticate header, which RFC 6750 §3 requires when a request has no usable token. To add it, pass the error and your API's resource identifier to createResourceServerChallenge from @entro314labs/entro-auth-oauth-provider, and send the returned headers. It returns a challenge for 401 and insufficient_scope errors, and undefined for any other error. Bearer challenges, including insufficient_scope, carry a resource_metadata link to your protected resource metadata.

The challenge depends on whether the request presented a token. When it sent a token that failed verification, for example an expired or revoked one, the Bearer challenge carries error="invalid_token" and an error_description (RFC 6750 §3.1), so the client knows it must replace that token. When it sent no credentials at all, or sent its Authorization header without the Bearer or DPoP scheme, for example with Basic or no scheme, the challenge has no error code, so the client knows it must authorize first. That challenge offers both a Bearer and a DPoP challenge, so the client can use either scheme (RFC 9449 §7.1). When your own code rejects a presented token, throw an APIError with status UNAUTHORIZED and error: "invalid_token" to get the same challenge.

Pass the failed request as request, as above. The challenge for a 401 then depends on the scheme the client used to send its token:

  • A request that uses the DPoP scheme gets a DPoP challenge for every 401, including an expired or revoked token (RFC 9449 §7.2). A client that supports only DPoP might not act on a Bearer challenge.
  • A request that uses the Bearer scheme gets a Bearer challenge, unless the failure is DPoP-specific. A DPoP-specific failure, such as an invalid proof, gets a DPoP challenge.
  • A request that uses any other scheme, such as Basic, or sends a token with no scheme, gets both a Bearer and a DPoP challenge with no error code.

If your framework has no Request, pass { authorizationHeader } as the request option. Without it, only a DPoP-specific error selects a DPoP-only challenge. A DPoP challenge lists the accepted proof algorithms in algs. Both schemes carry resource_metadata (RFC 9728 §5.1). For a resource identifier that is not a URL, such as a urn:, pass its metadata URL in resourceMetadataMappings, keyed by the identifier. Without that entry, createResourceServerChallenge throws for both schemes.

With request, an insufficient_scope 403 on a request that used the DPoP scheme also gets a DPoP challenge, such as DPoP error="insufficient_scope", scope="files:write", error_description="access token is missing required scope: files:write", resource_metadata="https://api.example.com/.well-known/oauth-protected-resource", algs="ES256" (RFC 9449 §7.1). Its scope names the missing scopes, as in the Bearer challenge, so the client knows which scopes to request when it authorizes again.

Browsers hide WWW-Authenticate from cross-origin scripts unless the response lists it in Access-Control-Expose-Headers, because it is not a CORS-safelisted response header. The returned headers include Access-Control-Expose-Headers: WWW-Authenticate, so a browser client on another origin can read resource_metadata, scope, and algs. Your CORS layer must also answer the 401 and 403 responses with Access-Control-Allow-Origin. If it sets its own Access-Control-Expose-Headers, add WWW-Authenticate to that list, since it can replace the value on the challenge.

RFC 6750 limits error_description to printable ASCII without " or \. To fit a description into that set, createResourceServerChallenge replaces each " with ' and each other character outside it with a space. When nothing is left, it leaves error_description out. The returned error's body keeps the original error and error_description.

If the API runs in the same process as your auth server, you can use the resource client instead. Its 401 and insufficient_scope errors already carry the challenge in headers.

lib/server-client.ts
import { createAuthClient } from "@entro314labs/entro-auth/client";
import { oauthProviderResourceClient } from "@entro314labs/entro-auth-oauth-provider/resource-client";
import { auth } from "@/lib/auth";

export const serverClient = createAuthClient({
  plugins: [oauthProviderResourceClient(auth)],
});

The defaults come from your auth server's resolved base URL. That URL includes basePath, such as https://auth.example.com/api/auth:

  • issuer defaults to the issuer the provider signs. It comes from jwt.issuer when the JWT plugin sets it, and otherwise from the base URL, normalized as discovery describes. When the keys are read from this auth instance in-process, the default also accepts that URL as you configured it, which tokens issued before 1.8 carry. When the keys are fetched from a URL, which is the case when you set jwksUrl or when the JWT plugin sets jwks.remoteUrl, the default is the normalized issuer alone, because RFC 9068 §4 requires an exact match for remote verification. An issuer you pass is the only value accepted.
  • Without jwksUrl, the signing keys are read from the auth instance in-process, with no request to its own /jwks endpoint. When the JWT plugin sets jwks.remoteUrl, the keys are fetched from that URL instead. Set jwksUrl to fetch them from another URL. With disableJwtPlugin, the provider issues only opaque access tokens, which have no signing keys to read, so verify them with remoteVerify, as shown in JWT or opaque tokens.
  • audience defaults to the base URL. See the warning below.

With a dynamic baseURL, the base URL is known only per request, so nothing defaults to it. jwt.issuer and jwks.remoteUrl still apply when the JWT plugin sets them. Pass audience, and any of issuer and jwksUrl the JWT plugin does not set, explicitly.

Do not rely on the default audience. It is the auth server's URL, not your API's identifier, and it is also the default aud of JWT plugin session JWTs. With the defaults, a signed-in user's session JWT can pass as an access token. Set audience to your API's resource identifier, and add typ: "at+jwt" and requiredClaims: ["azp"]. The MCP authorization specification says an MCP server must validate that a token was issued for it as the intended audience, so an MCP server should not use the default.

api/posts.ts
import { isAPIError } from "@entro314labs/entro-auth/api";
import { serverClient } from "@/lib/server-client";

export const POST = async (req: Request) => {
  try {
    const payload = await serverClient.verifyAccessTokenRequest(req, {
      verifyOptions: {
        issuer: "https://auth.example.com/api/auth",
        audience: "https://api.example.com",
        typ: "at+jwt",
        requiredClaims: ["azp"],
      },
      jwksUrl: "https://auth.example.com/api/auth/jwks",
      requiredScopes: ["write:post"],
    });
    return Response.json({ sub: payload.sub });
  } catch (error) {
    if (!isAPIError(error)) throw error;
    return Response.json(error.body, {
      status: error.statusCode,
      headers: error.headers,
    });
  }
};

If every JWT access token fails with a 401 invalid access token error, check that issuer matches the token's iss claim and audience matches its aud claim. The provider puts the resource the client requested in aud, such as https://api.example.com.

To accept bearer tokens alone on a route, use verifyBearerToken. It takes a raw token string and rejects DPoP-bound tokens.

Signing keys are cached for five minutes. If a refetch after that fails or times out, a key set fetched less than ten minutes ago still verifies tokens that name one of its keys, or name none, so a slow or unreachable auth server does not reject valid tokens right away. A key the issuer already rotated out can pass for up to ten minutes after the last successful fetch. Without a cached key set (a cold start, or a custom jwt.adapter.getJwks, whose keys are not cached), or for a token that names a key the set lacks, the failed refetch is reported as an error, as it is without this fallback. These windows are local choices and ignore the key set's Cache-Control header.

For DPoP-bound tokens:

  • The proof is checked against request.url. A proxy in front of the API must forward the external scheme, host, and path.
  • The replay store rejects a proof that was already used. The default store is in memory. It is safe only for a single instance. If your API runs on several instances or on serverless, pass a shared store, as below. The shared store records each proof where your auth instance keeps verification values: in secondary storage when you configure it without verification.storeInDatabase, and otherwise in the database.
api/posts.ts
import { createDpopReplayStore } from "@entro314labs/entro-auth/oauth2";
import { auth } from "@/lib/auth";

const replayStore = createDpopReplayStore(await auth.$context);

// Pass it with the other options, as in the example above:
// verifyAccessTokenRequest(input, { jwksUrl, verifyOptions, dpop: { replayStore } })

Require DPoP nonces

Your API can require a server-provided nonce in each DPoP proof, as the provider's endpoints can with dpop.nonce. The nonce stops a client from using proofs it signed ahead of time (RFC 9449 §9).

Pass dpop.nonce to verifyAccessTokenRequest, and choose its secret by where your API runs:

  • On the auth server's origin: use the auth secret and the provider's dpop.nonce.expiresIn. Clients keep one nonce per origin. With the same secret and lifetime, the nonce from a token response also works at your API.
  • On its own origin: use a separate secret. Share that secret across every instance of the API.

A DPoP request without a current nonce fails with a 401 use_dpop_nonce error. The error carries a fresh nonce in its DPoP-Nonce header. createResourceServerChallenge turns the error into the WWW-Authenticate: DPoP challenge the client expects. The challenge keeps the nonce in its own DPoP-Nonce header, sets Cache-Control: no-store, and adds DPoP-Nonce and WWW-Authenticate to Access-Control-Expose-Headers.

To send the next nonce on a successful response, call createDpopNonce with the same secret. Mark that response Cache-Control: no-store. Otherwise a cache can hand out an old nonce (§8.2). For browser clients, also add DPoP-Nonce to its Access-Control-Expose-Headers.

createResourceServerChallenge returns one of two challenge schemes:

  • Bearer challenges answer an invalid token with a 401 and a token without a required scope with a 403 insufficient_scope. They carry resource_metadata, the URL of your API's protected resource metadata (RFC 9728 §5.1). A request without a token gets a Bearer and a DPoP challenge together.
  • DPoP challenges answer a failed DPoP proof, including use_dpop_nonce, with a 401. They carry algs, the proof algorithms your API accepts (RFC 9449 §7.1), and resource_metadata, like Bearer challenges.
api/posts.ts
import { createResourceServerChallenge } from "@entro314labs/entro-auth-oauth-provider";
import { isAPIError } from "@entro314labs/entro-auth/api";
import {
  createDpopNonce,
  requestToResourceInput,
  verifyAccessTokenRequest,
} from "@entro314labs/entro-auth/oauth2";

const nonceSecret = process.env.API_DPOP_NONCE_SECRET!;
const audience = "https://api.example.com";

export const GET = async (req: Request) => {
  try {
    const payload = await verifyAccessTokenRequest(requestToResourceInput(req), {
      jwksUrl: "https://auth.example.com/api/auth/jwks",
      verifyOptions: {
        issuer: "https://auth.example.com/api/auth",
        audience,
        typ: "at+jwt",
        requiredClaims: ["azp"],
      },
      dpop: { nonce: { required: true, secret: nonceSecret } },
    });
    return Response.json(
      { sub: payload.sub },
      {
        headers: {
          "Cache-Control": "no-store",
          "DPoP-Nonce": await createDpopNonce({ secret: nonceSecret }),
        },
      },
    );
  } catch (error) {
    const challenge = createResourceServerChallenge(error, audience);
    if (challenge) {
      return Response.json(challenge.body, {
        status: challenge.statusCode,
        headers: challenge.headers,
      });
    }
    if (!isAPIError(error)) throw error;
    return Response.json(error.body, { status: error.statusCode });
  }
};

A nonce stays valid for expiresIn seconds, 300 by default. It is not bound to one client: any client can use it until it expires. The replay store still rejects each reused proof.

The resource client created with your auth instance takes dpop: { nonce: { required: true } }. It uses the auth secret and the provider's dpop.nonce.expiresIn by default. requireMcpAuth does the same, and adds the next nonce to the responses of DPoP requests.

JWT or opaque tokens

Your provider issues a JWT access token when the request names a resource and the JWT plugin is enabled. If either is missing, or the resource uses opaque access tokens, it issues an opaque token.

JWT access tokenOpaque access token
How the API verifies itLocally, with the JWKS (jwksUrl)Remotely, through /oauth2/introspect (remoteVerify)
Cost per requestNo network call (unless remoteVerify is set)One call to the auth server
ClaimsFrozen when the token is issuedPer-issuance accessTokenClaims stored when the token is issued. Other claims recomputed on every introspection

The simplest setup is to accept only JWT access tokens. It is fast, and your API needs no client credentials. verifyAccessTokenRequest checks the JWT's signature, iss, aud, and exp. It checks scope only against the requiredScopes you pass, and checks the token type only when you pass typ: "at+jwt". Pass both to get the validation RFC 9068 §4 requires. The cost is that the local check does not see an ended session. A JWT keeps passing the local check until it expires.

If your API also receives opaque tokens, have it introspect them:

  1. Register your API as a confidential client with token_endpoint_auth_method: "client_secret_post". remoteVerify sends credentials in the request body. If the client keeps the default method, client_secret_basic, introspection fails with invalid_client. Verification then throws a 500 introspection failed error.
  2. Link it to the resource.
  3. Pass its credentials as remoteVerify.

With remoteVerify set, the provider introspects tokens and checks any associated session. Set typ: "at+jwt" to check the JWT access-token header locally as well. With force: true, the resource server skips local signature and header checks. The Entro Auth provider still requires both typ: at+jwt and azp during introspection.

api/posts.ts
const payload = await verifyAccessTokenRequest(requestToResourceInput(req), {
  verifyOptions: {
    issuer: "https://auth.example.com/api/auth",
    audience: "https://api.example.com",
    typ: "at+jwt",
    requiredClaims: ["azp"],
  },
  jwksUrl: "https://auth.example.com/api/auth/jwks",
  remoteVerify: {
    introspectUrl: "https://auth.example.com/api/auth/oauth2/introspect",
    clientId: process.env.API_CLIENT_ID!,
    clientSecret: process.env.API_CLIENT_SECRET!,
  },
});

When you set audience, the audience check stops a token issued for another API on the same issuer from passing at yours. If the introspection response has no aud claim and you set an audience, the token is rejected. Set remoteVerify.allowMissingAudience: true only if you trust the issuer to bind the token to your API some other way.

Endpoints on the auth server

A plugin endpoint served by the auth server itself can verify the request in-process with verifyResourceRequest on the provider API. It needs no JWKS fetch, introspection client, or network call, and it accepts JWT and opaque access tokens alike.

reports-plugin.ts
import { getOAuthProviderApi } from "@entro314labs/entro-auth-oauth-provider";
import { createAuthEndpoint } from "@entro314labs/entro-auth/api";
import type { EntroAuthPlugin } from "@entro314labs/entro-auth/types";

export const reports = () =>
  ({
    id: "reports",
    endpoints: {
      listReports: createAuthEndpoint(
        "/reports",
        { method: "GET" },
        async (ctx) => {
          const provider = getOAuthProviderApi(
            ctx,
            ctx.context.getPlugin("oauth-provider")!.options,
          );
          const claims = await provider.verifyResourceRequest({
            audience: "https://auth.example.com/api/auth/reports",
            scopes: ["read:reports"],
          });
          return ctx.json({ owner: claims.sub });
        },
      ),
    },
  }) satisfies EntroAuthPlugin;

verifyResourceRequest reads the token from the Authorization header and checks it against the provider's own records. A revoked opaque token, a token whose session has ended, and a token whose client is disabled fail on the next request. A JWT access token cannot be revoked by itself, so without a session it stays valid until it expires. It then applies the same rules as UserInfo:

  • A DPoP-bound token must come with a valid proof for this request's method and URL. With dpop.nonce.required on, the proof must carry a current nonce, and the response carries the next one.
  • With audience, the token's aud must contain it (RFC 9068 §4). Without it, a token issued for any resource passes, so set it whenever your endpoint is a registered resource.
  • With scopes, the token must carry every scope listed.

It returns the token's claims in introspection form, including sub, client_id, scope, aud, and cnf. For a token issued to a user, sub is the user ID, even when the token carries a pairwise sub. When it rejects the token or request, it throws an error that is ready to send:

FailureStatusChallenge
No token, or a scheme other than Bearer or DPoP401Bearer and DPoP, with no error code
Unknown, expired, or revoked token, or aud mismatch401invalid_token
Missing, invalid, or replayed DPoP proof401DPoP with invalid_dpop_proof
Missing or expired DPoP nonce401DPoP with use_dpop_nonce and a DPoP-Nonce header
Missing scopes403insufficient_scope, naming every missing scope

The table describes the WWW-Authenticate challenge. A request with no token also gets a 401 body, { error: "invalid_request", error_description: "access token not found" }, which does not match the challenge. Branch on the status and the challenge, not on the body error.

When audience is a URL, the Bearer and DPoP challenges also point to its protected resource metadata. Without audience, or when audience is not a URL, such as a urn:, the challenges leave out resource_metadata. verifyResourceRequest does not read resourceMetadataMappings, so it never throws for a missing mapping. With scopes, the challenge for a request without a token names them in scope. Every challenge lists WWW-Authenticate in Access-Control-Expose-Headers.

A DPoP-bound token fails through auth.api, because there is no HTTP request to check the proof against. A bearer token works there.

verifyResourceRequest rethrows any error not listed in the table, such as a database failure, unchanged. Handle it like any other server error, not as an OAuth error.

requireActiveAccessToken on the provider API accepts only an active bearer token. It refuses a DPoP-bound token with 401 invalid_token, because a token string alone cannot prove the client holds the key. The error's headers carry a DPoP challenge and list WWW-Authenticate in Access-Control-Expose-Headers. If you catch the error, send those headers with the 401, because a client that supports only DPoP might not act on a Bearer challenge. Use verifyResourceRequest for a protected endpoint.

Introspection

/oauth2/introspect implements RFC 7662. The caller must authenticate as a registered client (§2.1), using any method that client is registered for, including private_key_jwt.

  • A parameter sent more than once returns 400 invalid_request. An empty value counts as omitted.
  • token_type_hint only sets which token type is checked first. A token sent with the wrong hint is still found.

An authenticated client can introspect an access token only when:

  • it is the client the token was issued to, or
  • it is a resource server linked to one of the token's resources.

To set up the second case, register your API as a resource and link the client to it. Any other caller gets { active: false }, the same response as for an unknown or expired token. Only the client that requested a refresh token can introspect it.

An access token tied to a session is reported inactive once that session ends. A refresh token without offline_access that was issued in a session is tied to that session too: it is reported inactive once the session expires or is deleted, and Entro Auth revokes it at sign-out. Device authorization and CIBA tokens have no associated session. A refresh token can lose offline_access when a refresh narrows its scopes. A refresh token with offline_access stays active after its session ends, until it expires or is revoked, and its response omits sid. See Back-channel logout.

For an access token, the introspection response includes extension access token claims, customAccessTokenClaims, per-resource customClaims, and the reserved claims the server owns (iss, sub, aud, scope, and similar). A JWT access token returns the claims signed at issuance. An opaque access token returns the per-issuance accessTokenClaims stored at issuance and recomputes the other claims at introspection. Claims that depend on the grant type therefore appear only for JWT access tokens. A refresh token response omits aud, extension claims, customAccessTokenClaims, and per-resource customClaims. See Claim precedence.

A callback that returns a reserved claim name has that claim dropped. See Custom claims.

When consent was given under a reference, such as an organization, introspection of opaque access tokens and refresh tokens also returns it as reference_id. A JWT access token carries reference_id as a claim.

Scopes and permissions

Scopes describe what a client may request on a user's behalf. Permissions describe what a user is allowed to do, and your API enforces them.

The simplest setup maps each scope to exactly one permission, such as read:post. If you need finer control, map each scope to several permissions in your API, and pass isScopeSatisfied to change how requiredScopes are matched.

Protected resource metadata

To advertise which authorization server protects your API, serve an RFC 9728 document at /.well-known/oauth-protected-resource. serverClient.getProtectedResourceMetadata() builds it for you. Its default authorization_servers entry is the issuer that discovery publishes. With a dynamic baseURL and no jwt.issuer, it has no default entry, so pass authorization_servers. The MCP plugin serves this document automatically.

app/.well-known/oauth-protected-resource/route.ts
import { serverClient } from "@/lib/server-client";

export const GET = async () =>
  Response.json(
    await serverClient.getProtectedResourceMetadata({
      resource: "https://api.example.com",
      authorization_servers: ["https://auth.example.com/api/auth"],
    }),
  );

On this page