You are currently viewing documentation for v1.8 (Beta)

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 better-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 "@better-auth/oauth-provider";
import { isAPIError } from "better-auth/api";
import {
  requestToResourceInput,
  verifyAccessTokenRequest,
} from "better-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 @better-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.

A request can send a token that fails verification, for example an expired or revoked one. Its Bearer challenge then carries error="invalid_token" and an error_description (RFC 6750 §3.1). A request that sent no token gets a challenge without an error code. The client can then tell a token it must replace from a request that needs authorization first. 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. A client that sends its token with the DPoP scheme then 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. Without request, only DPoP-specific failures, such as an invalid proof, get a DPoP challenge. A DPoP challenge lists the accepted proof algorithms in algs and has no resource_metadata. If your framework has no Request, pass { authorizationHeader } instead.

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 "better-auth/client";
import { oauthProviderResourceClient } from "@better-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 jwt.issuer when the JWT plugin sets it. Otherwise, it defaults to the base URL, which matches the issuer the provider signs.
  • jwksUrl defaults to jwks.remoteUrl when the JWT plugin sets it. Otherwise, it defaults to the base URL followed by jwks.jwksPath, which is /jwks by default.
  • 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"].

api/posts.ts
import { isAPIError } from "better-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.

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 needs database-backed verification storage, and rejects DPoP requests when only secondary storage is configured.
api/posts.ts
import { createDpopReplayStore } from "better-auth/oauth2";
import { auth } from "@/lib/auth";

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

// 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 a missing or 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).
  • 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 no resource_metadata.
api/posts.ts
import { createResourceServerChallenge } from "@better-auth/oauth-provider";
import { isAPIError } from "better-auth/api";
import {
  createDpopNonce,
  requestToResourceInput,
  verifyAccessTokenRequest,
} from "better-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, 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 issuedRecomputed 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, every token is introspected after the local JWT check. Introspection also confirms the session is still active. The typ check reads the JWT header, which the introspection result does not have, so only the local check applies it. Set force: true to skip the local check, including typ. Introspection reports a JWT as active only when it has azp, so session JWTs still fail with force: true.

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.

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. When a session is deleted, such as at sign-out, Better Auth revokes its refresh tokens that lack offline_access. A refresh token can lose offline_access when a refresh narrows its scopes. Introspection reports those tokens inactive. Other refresh tokens stay active after their session ends, until they expire or are revoked. When a refresh token outlives its session, the 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 claims recomputed at introspection. Per-issuance claims and 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 same issuer that the resource client verifies by default. 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"],
    }),
  );