> For clean Markdown of any page, append .md to the page URL.
> For a complete documentation index, see https://docs.trutee.app/llms.txt.
> For AI client integration (Claude Code, Cursor, etc.), connect to the MCP server at https://docs.trutee.app/_mcp/server.

# Authentication and organizations

> User API keys, OAuth, organization isolation, and integration capabilities.

The API accepts user API keys and OAuth 2.0 access tokens as bearer credentials. Both identify an authorized user. Trutee resolves an exact organization, verifies that user's current membership, and derives capabilities from the membership role on every request.

## Choose an authentication method

Use a **user API key** for scripts, server-to-server jobs, and integrations operated directly by one Trutee user. Use **OAuth** when your product needs an end user to authorize a client and select an organization through a consent flow.

Do not use organization API keys when individual user attribution is required. A shared organization credential cannot reliably identify which person performed an action.

## User API keys

Create a user API key from your Trutee user profile and copy it immediately. Store it in a server-side secret store; never place it in browser or mobile application code, source control, logs, URLs, or analytics.

Send the key as a bearer credential and identify the organization using the slug shown under **Dashboard → Organization Settings → General**:

```bash
curl "https://api.trutee.app/courses" \
  -H "Authorization: Bearer $TRUTEE_API_KEY" \
  -H "Trutee-Organization: $TRUTEE_ORGANIZATION" \
  -H "Trutee-Version: 2026-07-29"
```

The API key subject is the acting user. `Trutee-Organization` selects context but never grants access: Trutee verifies that the same user is still a member of that exact organization and fails closed if the slug, membership, or role is invalid. Changing organizations requires changing the header and rediscovering all opaque IDs and cursors.

User API keys are long-lived until they expire or are revoked. Give each integration its own descriptively named key, keep it in a secret manager, and revoke it immediately if it may have been exposed. A revoked or expired key returns `401 unauthorized`.

## OAuth onboarding and token flow

1. [Request Public API access](mailto:support@trutee.app?subject=Public%20API%20access). Include your company and technical contact, the organization that needs access, intended use case, production HTTPS redirect URI or URIs, and whether you need a course-approved test Tee Time. Trutee provisions the production integration and supplies the OAuth client ID, client secret, authorization endpoint, token endpoint, and issuer/resource metadata; client credentials and access tokens must stay in your secret store.
2. Redirect the authorized user to the supplied authorization endpoint with your client ID, an exact registered redirect URI, and a cryptographically random `state`. The user signs in and selects the approved organization during consent. Reject callbacks whose `state` does not match.
3. Exchange the returned authorization code at the supplied token endpoint from your server. Never exchange codes or store client credentials in browser or mobile application code.
4. Send the access token as `Authorization: Bearer <token>`. The selected organization is part of the resolved OAuth context; it is not a request parameter or caller-asserted header.
5. Renew tokens through the OAuth flow and metadata Trutee supplies. When renewal is unavailable, consent is revoked, the user changes organization, or the API returns an organization/authentication error, restart authorization and require organization selection again. Rediscover IDs after changing organizations.

## Provisioning handoff

Do not begin implementation until Trutee has supplied all of these values:

| Value                          | Store and use it as                                             |
| ------------------------------ | --------------------------------------------------------------- |
| OAuth client ID                | `TRUTEE_CLIENT_ID`                                              |
| OAuth client secret            | `TRUTEE_CLIENT_SECRET`; server-side secret only                 |
| Authorization endpoint         | `TRUTEE_AUTHORIZATION_ENDPOINT`                                 |
| Token endpoint                 | `TRUTEE_TOKEN_ENDPOINT`                                         |
| Registered redirect URI        | `TRUTEE_REDIRECT_URI`; must match exactly                       |
| Issuer/resource metadata       | OAuth validation configuration                                  |
| Approved organization and user | The organization selected during consent                        |
| Course-approved test plan      | Test course, Tee Time, guest identity, and cleanup expectations |

## OAuth profile

The first Public API integration uses this OAuth profile unless Trutee explicitly provisions different values:

| Property                       | Public API behavior                                                                                                                                            |
| ------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Client type                    | Confidential server-side web client                                                                                                                            |
| User grant                     | Authorization Code                                                                                                                                             |
| Token renewal                  | Refresh Token when a refresh token is issued                                                                                                                   |
| Client authentication          | HTTP Basic at the token endpoint                                                                                                                               |
| Organization                   | Selected by the user during consent and resolved from the token context                                                                                        |
| Scopes, audience, and resource | Do not invent or add values; use only values supplied during provisioning. API capabilities are derived server-side from the selected organization membership. |
| PKCE                           | Not required for the current confidential-client profile. If Trutee provisions it later, use S256; PKCE does not replace confidential-client authentication.   |

Do not use the Client Credentials grant. Every API token must continue to represent an authorizing user and the selected Integration Organization, including background reconciliation jobs.

Build the authorization redirect from the supplied endpoint using `response_type=code`, your client ID, exact redirect URI, and a cryptographically random `state`. Preserve any additional parameters supplied by Trutee. After validating the callback's `state`, exchange the code from your server:

| Authorization parameter | Value                                                                                                           |
| ----------------------- | --------------------------------------------------------------------------------------------------------------- |
| `response_type`         | `code`                                                                                                          |
| `client_id`             | The provisioned `TRUTEE_CLIENT_ID`                                                                              |
| `redirect_uri`          | The exact allowlisted `TRUTEE_REDIRECT_URI`                                                                     |
| `state`                 | A cryptographically random, single-use value bound to the user's server-side session                            |
| Additional parameters   | Include exactly the values supplied during provisioning. If PKCE is required, Trutee also supplies that policy. |

For example, the browser redirect has this shape; the endpoint and values shown are placeholders:

```text
https://authorization.example/authorize?response_type=code&client_id=client_example&redirect_uri=https%3A%2F%2Fintegration.example%2Foauth%2Fcallback&state=random-single-use-value
```

The authorization server redirects back with `code` and the same `state`:

```text
https://integration.example/oauth/callback?code=authorization-code&state=random-single-use-value
```

The callback can instead contain `error`, optional `error_description`, and the original `state`. Always validate and consume `state` before handling either outcome. Treat `access_denied` as a user cancellation, show a restart option, and do not exchange a code when any OAuth error is present. Reject callbacks containing both `code` and `error`, a missing or reused `state`, or a redirect URI that does not reach the exact registered server route.

Create the authorization URL and persist the state in an encrypted or signed server-side session before redirecting:

**`TypeScript`**

```typescript title="TypeScript"
import { randomBytes } from "node:crypto";

const state = randomBytes(32).toString("base64url");
const authorizationUrl = new URL(process.env.TRUTEE_AUTHORIZATION_ENDPOINT!);

authorizationUrl.searchParams.set("response_type", "code");
authorizationUrl.searchParams.set("client_id", process.env.TRUTEE_CLIENT_ID!);
authorizationUrl.searchParams.set(
  "redirect_uri",
  process.env.TRUTEE_REDIRECT_URI!,
);
authorizationUrl.searchParams.set("state", state);

// Save `state` in the user's server-side session, then redirect to:
console.log(authorizationUrl.toString());
```

**`Python`**

```python title="Python"
import os
import secrets
from urllib.parse import parse_qsl, urlencode, urlparse, urlunparse

state = secrets.token_urlsafe(32)
parsed_endpoint = urlparse(os.environ["TRUTEE_AUTHORIZATION_ENDPOINT"])
query = dict(parse_qsl(parsed_endpoint.query))
query.update(
    {
        "response_type": "code",
        "client_id": os.environ["TRUTEE_CLIENT_ID"],
        "redirect_uri": os.environ["TRUTEE_REDIRECT_URI"],
        "state": state,
    }
)
authorization_url = urlunparse(
    parsed_endpoint._replace(query=urlencode(query))
)

# Save `state` in the user's server-side session, then redirect to:
print(authorization_url)
```

At the callback, compare `state` using your framework's timing-safe session mechanism, consume it once, reject OAuth errors, and exchange the code only from your server. The token request is:

**`TypeScript`**

```typescript title="TypeScript"
const tokenRequest = new URLSearchParams({
  grant_type: "authorization_code",
  code: authorizationCode,
  redirect_uri: process.env.TRUTEE_REDIRECT_URI!,
});
const clientCredentials = Buffer.from(
  `${process.env.TRUTEE_CLIENT_ID}:${process.env.TRUTEE_CLIENT_SECRET}`,
).toString("base64");

const tokenResponse = await fetch(process.env.TRUTEE_TOKEN_ENDPOINT!, {
  method: "POST",
  headers: {
    Accept: "application/json",
    Authorization: `Basic ${clientCredentials}`,
    "Content-Type": "application/x-www-form-urlencoded",
  },
  body: tokenRequest,
});

if (!tokenResponse.ok) {
  throw new Error(`OAuth token exchange failed (${tokenResponse.status})`);
}

const tokens = (await tokenResponse.json()) as {
  access_token: string;
  token_type: "Bearer";
  expires_in: number;
  refresh_token?: string;
};
```

**`Python`**

```python title="Python"
import os
import requests

token_response = requests.post(
    os.environ["TRUTEE_TOKEN_ENDPOINT"],
    auth=(
        os.environ["TRUTEE_CLIENT_ID"],
        os.environ["TRUTEE_CLIENT_SECRET"],
    ),
    headers={"Accept": "application/json"},
    data={
        "grant_type": "authorization_code",
        "code": authorization_code,
        "redirect_uri": os.environ["TRUTEE_REDIRECT_URI"],
    },
    timeout=30,
)
token_response.raise_for_status()
tokens = token_response.json()
```

**`cURL`**

```curl title="cURL"
curl -X POST "$TRUTEE_TOKEN_ENDPOINT" \
  -u "$TRUTEE_CLIENT_ID:$TRUTEE_CLIENT_SECRET" \
  -H "Accept: application/json" \
  -H "Content-Type: application/x-www-form-urlencoded" \
  --data-urlencode "grant_type=authorization_code" \
  --data-urlencode "code=$TRUTEE_AUTHORIZATION_CODE" \
  --data-urlencode "redirect_uri=$TRUTEE_REDIRECT_URI"
```

A successful token response has this general shape. Exact fields and lifetimes come from the provisioning metadata:

```json
{
  "access_token": "access-token-value",
  "token_type": "Bearer",
  "expires_in": 3600,
  "refresh_token": "refresh-token-value"
}
```

Token endpoint failures use the OAuth JSON error shape:

```json
{
  "error": "invalid_grant",
  "error_description": "The authorization code or refresh token is no longer valid."
}
```

Handle the common cases deliberately:

| Error                                   | Integration response                                                                           |
| --------------------------------------- | ---------------------------------------------------------------------------------------------- |
| `invalid_grant`                         | Discard the failed code or refresh token and restart authorization. Never repeatedly retry it. |
| `invalid_client`                        | Stop and correct the provisioned client ID, secret, or token-endpoint authentication.          |
| `access_denied`                         | Treat consent as cancelled and let the user restart.                                           |
| `temporarily_unavailable` or HTTP `5xx` | Retry with exponential backoff, jitter, and a bounded attempt budget.                          |

Use `expires_in` to calculate expiry with a small clock-skew allowance. Refresh before starting work that may outlive the access token. If refresh returns a replacement refresh token, atomically replace the stored token only after the new token set is safely persisted; never log either token.

Persist the returned refresh token in your secret store. Background reconciliation still acts for the authorizing user and selected organization; a client-credentials-only token is not supported. Refresh without sending a user through consent again:

**`TypeScript`**

```typescript title="TypeScript"
const clientCredentials = Buffer.from(
  `${process.env.TRUTEE_CLIENT_ID}:${process.env.TRUTEE_CLIENT_SECRET}`,
).toString("base64");
const refreshRequest = new URLSearchParams({
  grant_type: "refresh_token",
  refresh_token: storedRefreshToken,
});

const refreshed = await fetch(process.env.TRUTEE_TOKEN_ENDPOINT!, {
  method: "POST",
  headers: {
    Accept: "application/json",
    Authorization: `Basic ${clientCredentials}`,
    "Content-Type": "application/x-www-form-urlencoded",
  },
  body: refreshRequest,
});

if (!refreshed.ok) {
  throw new Error(`OAuth token refresh failed (${refreshed.status})`);
}
const tokens = await refreshed.json();
```

**`Python`**

```python title="Python"
import os
import requests

refreshed = requests.post(
    os.environ["TRUTEE_TOKEN_ENDPOINT"],
    auth=(
        os.environ["TRUTEE_CLIENT_ID"],
        os.environ["TRUTEE_CLIENT_SECRET"],
    ),
    headers={"Accept": "application/json"},
    data={
        "grant_type": "refresh_token",
        "refresh_token": stored_refresh_token,
    },
    timeout=30,
)
refreshed.raise_for_status()
tokens = refreshed.json()
```

**`cURL`**

```curl title="cURL"
curl -X POST "$TRUTEE_TOKEN_ENDPOINT" \
  -u "$TRUTEE_CLIENT_ID:$TRUTEE_CLIENT_SECRET" \
  -H "Accept: application/json" \
  -H "Content-Type: application/x-www-form-urlencoded" \
  --data-urlencode "grant_type=refresh_token" \
  --data-urlencode "refresh_token=$TRUTEE_REFRESH_TOKEN"
```

Treat the exact endpoints, parameters, token lifetime, and renewal metadata supplied during provisioning as authoritative. Never log API keys, authorization codes, client secrets, access tokens, or refresh tokens.

Trutee manages OAuth client registration and redirect allowlisting. This API documentation does not expose or ask you to configure Trutee deployment secrets, preview credentials, or private-beta runtime settings.

The dated contract derives capabilities from the verified membership assigned during onboarding. Internal role names are not part of the public contract:

| Provisioned capability       | Courses | Public inventory | Expanded inventory | Reservation read/write |
| ---------------------------- | ------- | ---------------- | ------------------ | ---------------------- |
| Standard organization user   | Yes     | Yes              | No                 | No                     |
| API-enabled integration user | Yes     | Yes              | Yes                | Yes                    |

An unknown role returns `unsupported_organization_role`; it never inherits access. Missing OAuth organization context or a missing API-key `Trutee-Organization` header returns `organization_required`. A mismatched or missing membership returns `forbidden`.

The dated API derives authorization from the resolved organization and verified membership role; it does not treat unavailable custom credential scopes as an authorization boundary.

Authorization is always rechecked against the resolved principal. Availability offers and availability cursors are cryptographically principal-bound; Reservation-list cursors are filter- and page-size-bound and remain authorization-scoped when used. Opaque resource IDs are encrypted type-safe references, not bearer credentials. Switching the selected organization requires rediscovery; never treat an ID or cursor as proof of access or reuse it across organizations.