# Protect an API

> Register your API with Pontive and accept only access tokens issued for it, with pontkit's resource server in TypeScript or with any JWT library and the instance's JWKS, or by token introspection.

Source: https://www.pontive.com/docs/guides/protect-an-api

Your API accepts a request when it carries a Pontive access token that was issued **for that API**.
The token says who is calling (`sub`), for which client, with which scopes, and, when the caller acts
in an organization, which one and with which roles and permissions there.

## 1. Register the API [#1-register-the-api]

In the dashboard (**APIs**) or the [management API](/docs/api-reference/management/registered-apis),
register the API on the instance with:

- an **identifier**, usually its URL, e.g. `https://api.acme.com`. Tokens for the API carry it in
  `aud`, and clients name it as the `resource` parameter (RFC 8707) when they ask for a token;
- its **scopes**, e.g. `files:read` and `files:write`.

Apps of the instance may request the API's scopes by default. Service accounts and agents need an
explicit **client grant** naming the API and the scopes.

## 2. Get a token for the API [#2-get-a-token-for-the-api]

A token is issued for an API only when the request names it with `resource`. Without `resource`,
the token's `aud` is the client itself, and your API must refuse it.

A service account calling your API (machine to machine), with the client credentials grant:

```sh
curl -s -u "svc_...:$PONTIVE_CLIENT_SECRET" \
  -d grant_type=client_credentials \
  -d resource=https://api.acme.com \
  -d scope="files:read" \
  "https://<auth-domain>/oauth2/token"
```

A user-facing app passes `resource` on `/oauth2/authorize` (and may repeat it on the code exchange),
or on a `refresh_token` grant to get a token for another API the user's grant covers. A requested
`resource` that matches no API, or one the client may not request, is `invalid_target`; an API scope
asked for without `resource` is `invalid_request`.

## 3. Verify the token [#3-verify-the-token]

Every check below is required. Skipping `aud` lets a token issued for another API, or an app's own
token, through; skipping `typ` lets an ID token through.

| Check | Value |
| --- | --- |
| Signature | RS256, by a key in the instance's JWKS (`jwks_uri` in `https://<auth-domain>/.well-known/openid-configuration`) |
| `typ` header | `at+jwt` (an access token, RFC 9068) |
| `iss` | your auth domain, `https://<auth-domain>`; list each one if the instance also has a custom domain |
| `aud` | contains your API's identifier |
| `exp` | in the future (allow a minute of clock skew) |
| `scope` | contains the scope the route needs |

### TypeScript: `@pontive/pontkit-server` [#typescript-pontivepontkit-server]

```sh
npm install @pontive/pontkit-server
```

```ts title="pontive.ts"
import { createResourceServer } from "@pontive/pontkit-server/resource-server";

export const rs = createResourceServer({
  issuer: process.env.PONTIVE_ISSUER!, // https://<auth-domain>, or a list of them
  resource: "https://api.acme.com",    // the API's identifier, exactly as registered
  scopes: ["files:read", "files:write"],
});
```

Any Web-standard handler (Next.js route handlers, Hono, Cloudflare Workers, Bun, Deno):

```ts title="app/api/files/route.ts"
import { rs } from "@/pontive";

const guard = rs.requireBearer({ scopes: ["files:read"] });

export async function GET(request: Request) {
  const caller = await guard(request);
  if (caller instanceof Response) return caller; // 401 or 403, with WWW-Authenticate
  return Response.json({ user: caller.sub, org: caller.orgId ?? null, roles: caller.roles });
}
```

Express:

```ts
import express from "express";
import { requireBearer } from "@pontive/pontkit-server/resource-server/express";
import { rs } from "./pontive";

const app = express();

app.get("/files", requireBearer(rs, { scopes: ["files:read"] }), (req, res) => {
  res.json({ user: req.principal.sub });
});
```

Keys are fetched once and cached, so verifying costs no network call per request. The handler gets
a `Principal`:

| Field | |
| --- | --- |
| `sub`, `kind` | `usr_…` (`"user"`), `svc_…` (`"service_account"`) or `agt_…` (`"agent"`) |
| `clientId` | the client the token was issued to |
| `orgId` | the organization the token acts in, when it does |
| `roles`, `permissions` | the caller's effective roles and permissions in that organization, or on the instance when there is none |
| `scopes` | the granted scopes |
| `isDelegated`, `actor` | `true` when an agent acts for the user: `sub` is the user, `actor.sub` the agent. Check what it may do by token (below), never by `sub` alone |

The same resource server also serves the API's protected resource metadata (RFC 9728) that MCP
clients read: see [Protect an MCP server](/docs/sdk/mcp-server).

### Any other language: the JWKS [#any-other-language-the-jwks]

Fetch the instance's discovery document once, read `jwks_uri`, and verify with a JWT library that
caches the keys. Python, with PyJWT:

```python
import jwt  # pip install "pyjwt[crypto]"

ISSUER = "https://acme-x7k2p9qa-dev.auth.us.pontive.dev"
RESOURCE = "https://api.acme.com"

jwks = jwt.PyJWKClient(f"{ISSUER}/oauth2/jwks.json")  # cached after the first fetch

def verify(token: str, required_scope: str) -> dict:
    if jwt.get_unverified_header(token).get("typ") != "at+jwt":
        raise PermissionError("not an access token")
    key = jwks.get_signing_key_from_jwt(token).key
    claims = jwt.decode(
        token,
        key,
        algorithms=["RS256"],
        audience=RESOURCE,
        issuer=ISSUER,
        leeway=60,
        options={"require": ["exp", "sub", "iss", "aud"]},
    )
    if required_scope not in claims.get("scope", "").split():
        raise PermissionError("insufficient_scope")
    return claims
```

Go, with `golang-jwt` and `keyfunc`:

```go
import (
	"context"
	"errors"
	"slices"
	"strings"
	"time"

	"github.com/MicahParks/keyfunc/v3"
	"github.com/golang-jwt/jwt/v5"
)

const (
	issuer   = "https://acme-x7k2p9qa-dev.auth.us.pontive.dev"
	resource = "https://api.acme.com"
)

func newVerifier(ctx context.Context) (func(raw, scope string) (jwt.MapClaims, error), error) {
	keys, err := keyfunc.NewDefaultCtx(ctx, []string{issuer + "/oauth2/jwks.json"})
	if err != nil {
		return nil, err
	}

	return func(raw, scope string) (jwt.MapClaims, error) {
		claims := jwt.MapClaims{}
		token, err := jwt.ParseWithClaims(raw, claims, keys.Keyfunc,
			jwt.WithValidMethods([]string{"RS256"}),
			jwt.WithIssuer(issuer),
			jwt.WithAudience(resource),
			jwt.WithExpirationRequired(),
			jwt.WithLeeway(time.Minute),
		)
		if err != nil {
			return nil, err
		}
		if token.Header["typ"] != "at+jwt" {
			return nil, errors.New("not an access token")
		}
		granted, _ := claims["scope"].(string)
		if !slices.Contains(strings.Fields(granted), scope) {
			return nil, errors.New("insufficient_scope")
		}
		return claims, nil
	}, nil
}
```

Answer a missing or invalid token with `401` and `WWW-Authenticate: Bearer error="invalid_token"`,
and a token without the needed scope with `403` and `error="insufficient_scope"`.

The JWKS path above is the one Pontive's discovery documents name today (`/oauth2/jwks.json`); read
`jwks_uri` from discovery rather than hard-coding it if you can.

### Token introspection [#token-introspection]

When you cannot verify JWTs locally, ask the auth server (RFC 7662). `introspection_endpoint` in the
discovery document is `https://<auth-domain>/oauth2/introspect`, and the caller must authenticate:

```sh
curl -s -u "svc_...:$PONTIVE_CLIENT_SECRET" \
  -d token="$ACCESS_TOKEN" \
  "https://<auth-domain>/oauth2/introspect"
```

- A **service account** of the instance may introspect any token the instance issued.
- A **confidential app** sees only tokens issued to it or naming it in `aud`; any other token answers
  `{ "active": false }`.

An inactive, expired or unknown token is `{ "active": false }`. Introspection costs a network call per
request, and it also reflects a session revoked since the token was issued.

## Claims in a Pontive access token [#claims-in-a-pontive-access-token]

| Claim | |
| --- | --- |
| `iss`, `sub`, `aud`, `exp`, `iat`, `nbf`, `jti` | standard. `sub` is `usr_…`, `svc_…` or `agt_…` |
| `client_id` | the app, service account or agent the token was issued to |
| `scope` | space-separated granted scopes |
| `instance` | the instance id, `inst_…` |
| `sid` | the session, for user sign-ins |
| `org_id` | the organization the token acts in; absent when none |
| `roles` | the effective role keys in that organization, or on the instance root when there is no `org_id` |
| `permissions` | the permission keys those roles grant there |
| `act` | only on delegated tokens: `{ "sub": "agt_…" }`, the agent acting for the user |

The roles and permissions are a coarse snapshot of the caller's organization, re-read on every
refresh. Decisions about a specific object (this document, this project) belong to the
[authorization API](/docs/guides/organizations-and-roles#fine-grained-checks).

## Delegated calls from agents [#delegated-calls-from-agents]

When an agent acts for a user, `sub` is the user and `act.sub` the agent, and the token's authority is
the intersection of both. Do not read or write the user's data by `sub` alone: check the permission
by token with `createAuthorizationClient` from `@pontive/pontkit-server/authorization`, which evaluates
the pair. See [Permission-aware RAG](/docs/sdk/permission-aware-rag) for a worked example.
