Skip to content

How to protect an API with JWT access tokens

Register an API in Ostiary, request tokens with the resource parameter, and verify the JWT in your API: JWKS, audience, scopes, introspection and DPoP.

Published on 7 min read

Signing users in is only half of an identity server's job. The other half is letting your apps call your own APIs, and letting those APIs decide, on every request, whether to say yes. Ostiary, the self-hosted identity provider built on Better Auth, does this with JWT access tokens: you register each API in the admin console, apps ask for a token for that API, and the API verifies the token locally against Ostiary's public keys. This post walks through the whole path, from registering the API to checking the token, with the standards each step relies on.

Why an access token needs an audience

An access token is a bearer credential: whoever holds it can use it. If one token worked on every API you run, a token leaked from your least critical service would open the most critical one. The fix is to name the intended recipient in the token itself, in the aud (audience) claim, and to have each API refuse tokens that are not addressed to it.

OAuth has a standard way for an app to say which API it wants a token for: the resource parameter of Resource Indicators for OAuth 2.0 (RFC 8707). Ostiary uses it. A token requested with resource=https://api.example.com has that URL as its audience. A token requested without resource is opaque and is meant only for Ostiary's own UserInfo endpoint, not for your APIs.

Register the API in Ostiary

In the admin console, open APIs and fill in Register an API:

  • Identifier: an absolute URL, usually the API's base URL, such as https://api.example.com. It becomes the tokens' aud and cannot be changed later.
  • Name: a label for the console.
  • Scopes: what the API lets clients do, for example orders:read orders:write. The OpenID Connect scopes are refused here, since every client has them already.

New APIs and scopes reach the auth server within a minute, without a redeploy, and the discovery document lists the scopes in scopes_supported. To provision an instance from configuration instead, OAUTH_API_AUDIENCES and OAUTH_API_SCOPES declare them from the environment, as the deployment guide shows.

Scopes stay with their API

A token for one API never carries another API's scopes: a request for resource=B with scope=apiA:write gets that scope dropped, or invalid_scope when nothing allowed is left. With Only issue these scopes for this API, a token carries the API's own scopes and the OpenID Connect ones, nothing else.

You can also limit who may call an API. Under Applications, Only linked applications restricts tokens to the apps you tick; any other app gets invalid_target, including when it refreshes a token it already has.

Get a token for the API

On behalf of a user

An app that signs users in adds resource and the API's scopes to its authorization request, next to the usual PKCE parameters:

https://auth.example.com/api/auth/oauth2/authorize
  ?response_type=code
  &client_id=CLIENT_ID
  &redirect_uri=https://app.example.com/callback
  &scope=openid profile email offline_access orders:read
  &resource=https://api.example.com
  &code_challenge=...
  &code_challenge_method=S256

The user approves the scopes on the consent screen. The code exchange and later refreshes keep the resource, so the app's token requests need nothing more. When the token also has the openid scope, its aud is an array: the API, plus Ostiary's UserInfo URL, so the same token works on both.

For a service, with no user

Background jobs and backends use the client credentials grant (RFC 6749, section 4.4). Register the client in Applications as Machine-to-machine (client credentials) and tick the scopes it may request under APIs and scopes. Then:

curl -s https://auth.example.com/api/auth/oauth2/token \
  -u "$CLIENT_ID:$CLIENT_SECRET" \
  -d grant_type=client_credentials \
  -d scope=orders:read \
  -d resource=https://api.example.com

The token's sub is the client ID, and there is no ID token or refresh token, since no one signed in.

Verify the token in your API

Ostiary's access tokens follow the JWT profile for OAuth 2.0 access tokens (RFC 9068): the header's typ is at+jwt, which keeps an ID token from being accepted where an access token is expected. They are signed with Ed25519 (the EdDSA algorithm of RFC 8037), and the public keys are published as a JSON Web Key Set (RFC 7517) at https://auth.example.com/api/auth/jwks.

Your API checks, on every request:

  • the signature, with the JWKS key named by the token's kid;
  • iss: https://auth.example.com/api/auth;
  • aud: your API's identifier;
  • exp, and typ: at+jwt;
  • the scope the endpoint needs, in the space-separated scope claim.

No call to Ostiary is needed per request. With the jose library, which runs in Node.js, Deno, Bun, Cloudflare Workers and edge runtimes:

import { createRemoteJWKSet, jwtVerify } from "jose";

const ISSUER = "https://auth.example.com/api/auth";
const JWKS = createRemoteJWKSet(new URL(`${ISSUER}/jwks`));

export async function verify(token: string, scope: string) {
  const { payload } = await jwtVerify(token, JWKS, {
    issuer: ISSUER,
    audience: "https://api.example.com",
    typ: "at+jwt",
  });
  const scopes = typeof payload.scope === "string" ? payload.scope.split(" ") : [];
  if (!scopes.includes(scope)) throw new Error("insufficient_scope");
  return payload;
}

Answer a missing or invalid token with 401 and WWW-Authenticate: Bearer error="invalid_token", and a valid token without the right scope with 403 and error="insufficient_scope", the error codes of RFC 6750. The Protect an API guide has a complete version, and one using Better Auth's resource client, which sends those answers for you.

What the token tells you

Besides the standard claims, a user's access token carries azp and client_id (the app it was issued to), sid (the user's session) and role, the user's platform role, such as user or admin, so your API can authorize on it without a database lookup. Each API can add its own custom claims under APIs > Tokens, and each application can add claims from user attributes; the tokens and claims reference lists them all.

Key rotation needs nothing from your API

Ostiary rotates its signing keys on a schedule, or at once with Rotate now, and keeps the previous key in the JWKS for a grace period. An API that picks keys by kid and fetches the JWKS again on an unknown one, as createRemoteJWKSet does, keeps working through a rotation. Only an API that pins a single public key has to be updated. The OpenID Connect provider post covers the keys in more detail.

When a local check is not enough

A JWT stays valid until it expires: a local check cannot know that the user signed out a minute ago. Ostiary's access tokens last one hour by default, and APIs > Tokens can shorten that per API, along with the refresh token lifetime.

When your API needs to know right now, it can ask Ostiary through token introspection (RFC 7662). Introspection also checks that the user's session still exists, and it works for opaque tokens. It needs a confidential client, which may introspect its own tokens and tokens for any API it is linked to. Anything else, and any expired, revoked or unknown token, gets {"active": false}.

Bind tokens to a key with DPoP

A bearer token works for anyone who steals it. DPoP (RFC 9449) binds the token to a key the client holds. Turn on Require DPoP-bound tokens for an API, and clients must send a DPoP proof with their token request, then a fresh proof with every call to your API, as Authorization: DPoP <token>. The token carries the key's thumbprint in cnf. Ostiary accepts proofs signed with EdDSA, ES256 and ES512. On the API side, Better Auth's resource client checks the proof and its binding to the token.

Tokens or API keys?

Access tokens suit apps that sign users in and services with their own credentials. For a script that a person runs against your API, a long-lived key is often simpler: Ostiary also lets users and organizations create API keys for one of your APIs and some of its scopes, which your API verifies with Ostiary. MCP servers are APIs too: the MCP and dynamic client registration post shows how AI agents get tokens for them.

Try it

APIs, scopes, machine clients, introspection and DPoP come with every Ostiary instance, next to OpenID Connect sign-in for your apps. Deploy your own, register an API under APIs, and verify your first token with the snippet above.

Related articles

How Ostiary lets MCP clients and AI agents register themselves over OAuth: public PKCE clients only, scope limits, reused clients and RFC 9728.
Move users from Auth0 to Ostiary with a dry run first. Imported bcrypt hashes keep working and become scrypt at sign-in, with no password reset.
How Ostiary tells your apps when users change: user and membership webhook events, Standard Webhooks signatures, retries, and a receiver to copy.