# Set up API authentication and authorization

> Enable JWT or custom auth in 10xGraph, map roles to permissions, set how far each role can see (own, tenant or all), and keep each user's data private.

Source: https://10xgraph.com/docs/server/auth
Last updated: 2026-11-25

Authentication answers "who is calling the API?" Authorization answers "what may they do, and whose data may they see?" In 10xGraph both live under one `auth` key in `10xgraph.json`. This guide covers JWT and custom auth, roles and permissions, reach, ownership, and the checks the server runs at boot.

10xGraph is a resource server. It verifies tokens and reads claims. It does not issue tokens, store users or talk to an identity provider. Anything that needs a database or an identity provider lookup goes in your own `BaseAuth` class.

For the full picture of what the server enforces and what it leaves to you, see the [security model](/docs/production/security-model). To read the caller inside tools and nodes, see [Authorization scopes](/docs/guides/authorization-scopes).

## The big picture

Each request goes through the same steps on every transport (HTTP, WebSocket, AG-UI, live):

1. **Authenticate.** `BaseAuth.authenticate` verifies the credential and returns claims. A failure is 401 (close code 1008 on a WebSocket).
2. **Resolve.** The server turns the claims into an `Identity`: `user_id`, tenant values, roles, permissions and reach. A token with a missing tenant claim or a malformed roles or permissions claim is 401. It never falls back to a default role or reach.
3. **Authorize.** `BaseAuth.authorize(identity, permission, resource)` decides. A refusal is 403 with `Missing required permission: <permission>`.
4. **Run.** The identity goes into the run config as `config["user"]`. Storage filters every query by the identity's reach, so a foreign thread, message, memory, file or run answers 404.

Auth is opt-in. With `"auth": null` no check runs and no thread has an owner.

## Quick start with JWT

JWT needs no code: the server verifies a bearer token with a shared secret or public key.

1. **Install the JWT extra**

   ```bash
   pip install "10xgraph-api[jwt]"
   ```

2. **Set environment variables**

   Generate a secret and put these in your `.env` file:

   ```bash title=".env"
   JWT_SECRET_KEY=<generate-with: python -c 'import secrets; print(secrets.token_urlsafe(48))'>
   JWT_ALGORITHM=HS256
   ```

   `JWT_ALGORITHM` must be one of `HS256`, `HS384`, `HS512`, `RS256`, `RS384`, `RS512`, `ES256`, `ES384`, `ES512`, `PS256`, `PS384`, `PS512` or `EdDSA`. `none`, an empty value or an unknown value stops startup. Startup also stops if PyJWT is not installed, and the `auth` value must be exactly `"jwt"`. The server refuses a short HS* secret at startup when `MODE=production`, and warns otherwise. RFC 7518 requires HMAC secrets to be at least 32 bytes for HS256. `JWT_ALGORITHM` defaults to `HS256`.

3. **Enable JWT in 10xgraph.json**

   ```jsonc title="10xgraph.json"
   {
     "agent": "graph.agent:app",
     "env": ".env",
     "auth": "jwt"
   }
   ```

4. **Send bearer tokens from clients**

   Every request must carry the token in the `Authorization` header:

   ```bash
   curl -X POST http://localhost:8000/v1/graph/invoke \
     -H "Authorization: Bearer $TOKEN" \
     -H "Content-Type: application/json" \
     -d '{"messages": [{"role": "user", "content": [{"type": "text", "text": "hello"}]}]}'
   ```

> **Keep the signing secret safe**
>
> Anyone who holds `JWT_SECRET_KEY` can mint a token for any `user_id`. Never commit it, never bake it into a container image, and inject it at deploy time from a secret manager. Use HTTPS everywhere. To rotate without logging everyone out, list the old key in `JWT_SECRET_KEYS` while new tokens use `JWT_SECRET_KEY` (see [Rotating the signing key](/docs/reference/api-cli/auth#rotating-the-signing-key)). `JWT_MAX_TOKEN_AGE_SECONDS` caps how old a token may be.

## How do credentials reach the server?

### HTTP requests

The server reads a standard bearer credential from the `Authorization` header:

| Situation | HTTP status | Error code |
|---|---|---|
| No header | 401 | `INVALID_TOKEN` |
| Expired token | 401 | `EXPIRED_TOKEN` |
| Bad signature, or mismatched `iss`/`aud` | 401 | `INVALID_TOKEN` |
| Valid signature but no `user_id` claim | 401 | `INVALID_TOKEN` |
| `user_id` that is not a non-empty string or whole number (empty, boolean, float, list, object) | 401 | `INVALID_TOKEN` |
| `scope` or `scopes` claim of the wrong type | 401 | `INVALID_TOKEN` |
| Tenant claim missing, or `user_id` with the reserved `__system__` prefix | 401 | `INVALID_TOKEN` |
| Token revoked | 401 | `REVOKED_TOKEN` |
| Token revocation on and no usable `jti` claim | 401 | `INVALID_TOKEN` |
| All auth/authorization checks pass | 200 | (success) |

To pin tokens to your service and prevent replay across services, set `JWT_ISSUER` and `JWT_AUDIENCE` in your environment. Set both in production when the same signing key or identity provider also issues tokens for other services, so a token minted for another service is rejected here.

`JWT_ISSUER` and `JWT_AUDIENCE` are both off when unset or empty. With `JWT_ISSUER` unset, the issuer is not checked: a token with any `iss`, or none, is accepted. With it set, the token must carry `iss` and it must match exactly. With `JWT_AUDIENCE` unset, a token without `aud` is accepted, but a token that carries an `aud` claim is refused. With it set, the token must carry `aud` and it must match. A failure of either check answers 401 `INVALID_TOKEN`.

### WebSocket connections

WebSocket routes (`/v1/graph/ws`, `/v1/graph/live`) accept auth via the `Sec-WebSocket-Protocol` header (the standard subprotocol negotiation):

```javascript
const ws = new WebSocket(
  "ws://localhost:8000/v1/graph/ws",
  ["10xgraph-bearer", TOKEN]
);
```

The subprotocol list works as: the server looks for `10xgraph-bearer` (or the legacy `agentflow-bearer`), treats the next item as the token, and responds with the matching subprotocol. The server also accepts the `Authorization` header. A `?token=` query parameter is not accepted, because it would land in URLs and logs. The subprotocol works on WebSocket routes only; HTTP routes take the `Authorization` header alone. If no credential is found, the connection is rejected with close code `1008` (policy violation).

## How does the user reach your code?

The server builds an `Identity` from the verified claims and puts it in the run config as `config["user"]`. A tool or node that declares a `config` parameter receives it. Framework-injected parameters are hidden from the tool schema the model sees.

```python title="graph/tools/orders.py"
from tenxgraph.core.authz import get_identity

def list_my_orders(config: dict) -> list[dict]:
    """List the caller's recent orders."""
    identity = get_identity(config)  # None when auth is off
    return db.orders_for(identity.user_id)  # From the verified token, never a tool argument
```

`Identity` is a frozen model with `user_id`, `kind` (`user` or `system`), `tenant`, `roles`, `permissions`, `reach` and the raw `claims`. `identity.can("store:write")` checks one permission. See [Authorization scopes](/docs/guides/authorization-scopes) for the full guide.

User IDs starting with `__system__` are reserved for shared data (agent memory, RAG knowledge bases) and system identities. The server refuses a token that carries one (HTTP 401 "This user id is reserved", WebSocket close code 1008), so no caller can act as a shared owner.

Never take a user ID from a tool argument. The model chooses tool arguments; a prompt-injected model could ask to see another user's data. Trust the server-verified identity.

## The `auth` key

Everything about auth sits under one key. `method` picks who verifies the credential. The RBAC keys next to it apply to whichever method you choose.

```json title="10xgraph.json"
{
  "auth": {
    "method": "jwt",
    "roles_claim": "roles",
    "tenant_claims": ["org_id"],
    "roles": {
      "member": {
        "permissions": ["graph:*", "threads:*", "store:*", "files:*", "tasks:trigger", "tasks:read", "tasks:cancel"],
        "reach": "own"
      },
      "org_admin": {"inherits": ["member"], "permissions": ["admin:read"], "reach": "tenant"},
      "super_admin": {"permissions": ["*"], "reach": "all"}
    },
    "default_role": "member",
    "system_identities": {
      "nightly": {"roles": ["member"], "tenant": {"org_id": "acme"}}
    }
  }
}
```

Every key (`method`, `path`, `roles`, `roles_claim`, `permissions_claim`, `tenant_claims`, `default_role`, `system_identities`) is described in [The auth object](/docs/reference/api-cli/auth#the-auth-object). For `system_identities`, see [Background tasks](/docs/server/background-tasks).

With only `"auth": "jwt"`, every authenticated user gets the default permission set (everything except `admin:*`) with reach `own`.

### Where permissions come from

You pick one source. The framework defines no role meanings.

| Source | Config | Result |
|---|---|---|
| Default | no RBAC keys | Every authenticated user gets the default set, reach `own`. |
| Roles | `roles` (and optionally `roles_claim`) | Permissions are the union of the caller's roles, including inherited ones. Reach is the widest reach among them. Role names in the token that are not in `roles` are ignored. |
| Permissions | `permissions_claim` | The token lists permissions. Unknown names are ignored. A missing claim means no permissions. Reach is `own`. |

The claim may be a list of strings or one space-separated string. Anything else is 401. A token with no roles claim takes `default_role` when you set one, otherwise it holds no role and no permission.

Token `scope` and `scopes` claims only narrow. Effective permissions are the granted set intersected with the permission-shaped entries (those that contain `:` or equal `*`). Plain OAuth scopes such as `openid profile` are ignored. A permission-shaped scope the registry does not know narrows to nothing.

### The permission registry

Permissions are `resource:action` and come from one list. A role that names anything else refuses to boot. The resources, their actions and the permission each route needs are listed in [Permissions](/docs/reference/api-cli/auth#permissions). Tool permissions (`tools:<name>`) are checked by core's `ToolGuard`, never by a route; see [Zero-trust agents](/docs/security/zero-trust-agents#on-the-api-server).

Wildcards: `resource:*` grants every action of a resource, and `*` grants everything. The default set is every permission except `admin:*`, and it has no tool permissions: a tool behind a `ToolGuard` rule is denied until a role or token claim grants `tools:<name>` or `tools:*`.

### Reach: how far a caller sees

Reach says whose data a caller can see. It is set per role and is never a fallback: a missing or unknown reach refuses to boot (config) or denies (token, custom `authorize`).

The three values (`own`, `tenant`, `all`) and what each matches are in [Reach](/docs/reference/api-cli/auth#reach). `tenant` needs `tenant_claims` and a checkpointer with tenant columns.

Reach widens **reads, lists, deletes and stop only**. Runs and state or message writes always stay on the caller's own threads, admins included. Nobody runs inside another user's thread. Boot logs a warning for every role with reach `all`.

## Ownership lives in storage

There is no ownership cache and no ownership backend to configure. Every storage query filters by the caller's reach, so:

- A thread, message, memory, file or run outside the caller's reach answers **404**, the same as one that does not exist. Nothing reveals that the id exists.
- Each thread route makes one scoped read before the run lock and before any response header. That read gives the 404 and enforces [`runs.thread_ids`](/docs/reference/api-cli/configuration#thread_ids).
- Deleting a thread outside the caller's reach answers 404 and does no file or telemetry cleanup.
- With auth off there is no identity, so no thread has an owner.

Use a durable, shared checkpointer such as `PgCheckpointer` in production. Tenant isolation needs tenant columns on both the checkpointer and the store, see [Multi-tenant data](/docs/guides/multi-tenant-data).

## Who am I: `GET /v1/me`

`GET /v1/me` returns what the server resolved for the caller. A UI can use it to show or hide views.

```json
{"data": {"user_id": "u-42", "tenant": {"org_id": "acme"}, "roles": ["member"], "permissions": ["graph:invoke", "graph:stream", "threads:read"], "reach": "own"}}
```

`permissions` is sorted. An identity with no restriction reports `["*"]`. With auth off the answer is `{"auth": "off"}`.

## Custom authentication and authorization

Subclass `BaseAuth` and implement `authenticate`. Optionally override `authorize`.

Reference: [BaseAuth](/docs/reference/api-cli/auth) · Source: [base_auth.py](https://github.com/10xGraph/10xgraph-api/blob/main/tenxgraph_api/src/app/core/auth/base_auth.py)

```python title="auth/custom_auth.py"
from fastapi import HTTPException
from tenxgraph_api import BaseAuth

class ApiKeyAuth(BaseAuth):
    async def authenticate(self, request, response, credential):
        api_key = request.headers.get("X-API-Key")
        if not api_key or not verify_key(api_key):
            raise HTTPException(status_code=401, detail="Invalid API key")
        return {"user_id": "service-account", "roles": ["service"], "org_id": "acme"}
```

```json title="10xgraph.json"
{
  "auth": {
    "method": "custom",
    "path": "auth.custom_auth:ApiKeyAuth",
    "tenant_claims": ["org_id"],
    "roles": {"service": {"permissions": ["graph:invoke", "graph:stream"], "reach": "own"}}
  }
}
```

To call other services as the user, the server also puts a `UserCredential` in `config["credential"]` (the verified bearer token by default). Override `async BaseAuth.downstream_credential(self, connection, credential, claims)` to supply a different one, such as a session cookie or API key. Clients cannot set `credential` themselves. See [Calling services as the user](/docs/guides/call-services-as-the-user).

The `path` accepts `auth_app:Cls`, `auth_app.py:Cls`, `pkg.mod:Cls` and `pkg/mod.py:Cls`.

### `authenticate(request, response, credential)`

- Required, and **async**: declare it `async def`. The server awaits it, so a slow lookup does not block the event loop.
- Returns the verified claims as a dict. It must include `user_id`. Every other key lands in `identity.claims`.
- Raise `HTTPException` (your status) or `UserAccountError` (401) to refuse. On a WebSocket both become a clean 1008 close.
- Derive `user_id` and tenant values only from the verified credential, never from a client-set header or query parameter.
- Set `reusable_within_request = True` on the class only if `authenticate` is a pure function of the credential with no response side effects. Then the rate limiter's verified result is reused instead of verifying twice.

### `authorize(identity, permission, resource=None)`

- Optional and `async`. The default is `identity.can(permission)`, which applies the built-in RBAC.
- `permission` is `resource:action`, for example `threads:read`. `resource` is the id the request targets (thread id, memory id, namespace, file id, or the task name for a background task), or `None`.
- It takes no request, so the jobs worker can call it too.
- Return `True` to allow or `False` to answer 403. If it raises, the request fails. It never counts as allowed.
- If you override it and also set `roles`, the roles apply only when your code calls `await super().authorize(...)`. Boot warns about this.

```python
class MyAuth(BaseAuth):
    async def authenticate(self, request, response, credential): ...

    async def authorize(self, identity, permission, resource=None):
        if not await super().authorize(identity, permission, resource):
            return False  # keep the role table as the first gate
        return await my_extra_rule(identity, permission, resource)
```

A custom `authorize` decides permissions only. Reach still comes from the identity, which `auth.roles` resolves from your claims. A database recipe is [below](#recipes-for-a-custom-authorize).

## Revoke tokens

With auth on, set `cache_store.token_revocation` to `true` and the server refuses revoked tokens (401, code `REVOKED_TOKEN`). Revocations live in the cache store, so use `"type": "redis"` for them to reach every worker. Revoke from your own code with `revoke_user` or `revoke_token`, which write to the cache store the server uses:

```python
from injectq import InjectQ
from tenxgraph_api import BaseCacheStore, revoke_token, revoke_user

async def log_out_everywhere(user_id: str) -> None:
    cache = InjectQ.get_instance().get(BaseCacheStore)  # the server's cache store
    await revoke_user(cache, user_id)  # every token issued so far

# one token: await revoke_token(cache, jti, expires_at=exp)
```

`revoke_user` keys the revocation by `user_id` alone, not by tenant. Your identity provider must give user ids that are unique across tenants; if two tenants can share a `user_id`, revoking one revokes both.

```json title="10xgraph.json"
{
  "auth": "jwt",
  "cache_store": {"type": "redis", "token_revocation": true}
}
```

With revocation on, every token must carry a `jti` claim, including tokens from a custom `BaseAuth` class. The status codes, the `jti` rule and the fail-closed behavior are in [Token revocation](/docs/reference/api-cli/auth#token-revocation).

## Boot-time refusals

One validator runs at boot, in `10xgraph config`, `10xgraph audit` and `10xgraph build`. A setup the server would refuse cannot be saved in the editor, fails `audit`, and shows as a warning in `build`.

The full list of refused and warned setups is in [Boot-time checks](/docs/reference/api-cli/auth#boot-time-checks).

## Recipes for a custom `authorize`

`authorize` is where checks that need a lookup belong.

### Database lookup

Use this when access rules live in your own table. The query uses `asyncpg` with a pool you create once at startup. It keeps the built-in role check as the first gate.

```python title="auth/db_auth.py"
import asyncpg
from tenxgraph_api import BaseAuth

class DbAuth(BaseAuth):
    pool: asyncpg.Pool  # create once, for example at app startup

    async def authenticate(self, request, response, credential):
        ...  # verify the credential, return {"user_id": ..., "org_id": ...}

    async def authorize(self, identity, permission, resource=None):
        if not await super().authorize(identity, permission, resource):
            return False
        if permission.startswith("threads:") and resource is not None:
            return bool(await self.pool.fetchval(
                "SELECT EXISTS (SELECT 1 FROM project_members WHERE user_id = $1 AND thread_id = $2)",
                identity.user_id, resource,
            ))
        return True
```

The lookup runs on every guarded request, so index it and cache short-lived answers yourself if it is hot. Storage still filters by reach after `authorize` passes.

## Production deployment checklist

### Verify auth is enforced

Test without a token:

```bash
curl -X POST http://127.0.0.1:8000/v1/graph/invoke \
  -H "Content-Type: application/json" \
  -d '{"messages": [{"role": "user", "content": [{"type": "text", "text": "hello"}]}]}'
```

Expected: HTTP 401, code `INVALID_TOKEN`, before any graph execution.

Then check who the server thinks you are:

```bash
curl http://127.0.0.1:8000/v1/me -H "Authorization: Bearer <TOKEN>"
```

Expected: HTTP 200 with your `user_id`, `roles`, `permissions` and `reach`. Then ask for a thread another user owns and expect 404.

### Common failures to expect

| Error | Likely cause | Fix |
|---|---|---|
| 401 `INVALID_TOKEN` (no credential) | No credential presented | Attach `Authorization: Bearer <token>` |
| 401 `EXPIRED_TOKEN` | Token `exp` is in the past | Refresh the token; check server and issuer clock skew |
| 401 `INVALID_TOKEN` | Bad signature or no `user_id` claim | Verify `JWT_SECRET_KEY`, `JWT_ALGORITHM`, and that the issuer emits `user_id` |
| 401 `INVALID_TOKEN` ("Invalid token, please login again") | A configured tenant claim is missing, or the roles or permissions claim is malformed | Add the claim, or fix its type (list of strings or one space-separated string) |
| 401 `INVALID_TOKEN` ("Invalid token, jti missing") | `cache_store.token_revocation` is on and the token has no `jti` | Issue tokens with a `jti` claim, or turn revocation off |
| 401 `REVOKED_TOKEN` | The token or all of the user's tokens were revoked | Sign in again for a new token |
| 403 `Missing required permission: <resource>:<action>` | The caller's roles do not grant it | Add the permission to a role, or give the user the role |
| 404 on a thread you expect to exist | It belongs to another user or tenant, or does not exist | Check `GET /v1/me` for reach and the token's tenant claim |
| 500 `JWT_SETTINGS_NOT_CONFIGURED` on every request | `JWT_SECRET_KEY` is not set | Set it (32+ bytes for HS*) |
| Refuses to boot, naming `authorization` or `graph_introspection` | Removed keys | See [Upgrade to 1.0](/docs/project/upgrade-to-1.0#auth-roles-and-reach) |

### Boot guard

Every non-public route is checked at startup to carry a `RequirePermission` guard. If a route lacks one, the server refuses to start:

```
RuntimeError: Refusing to start: the following routes are not protected:
  - POST /v1/my-new-endpoint
```

This is intentional: a forgotten guard becomes a deploy-time error, not a silent open endpoint. `/ping` and `/health/ready` are the only public routes, plus the Prometheus scrape path when the `metrics` block turns it on.

## See also

- [Authorization scopes](/docs/guides/authorization-scopes): Read the caller and check permissions inside tools and nodes
- [Multi-tenant data](/docs/guides/multi-tenant-data): Tenant columns and reach in storage
- [Calling services as the user](/docs/guides/call-services-as-the-user): Token exchange, M2M and self-issued tokens for MCP and local tools
- [Configure the API server](/docs/server/configure): Set `auth` and other keys in `10xgraph.json`
- [Troubleshooting auth](/docs/troubleshooting/api-server): Debug auth and CORS failures
- [REST API: auth reference](/docs/reference/api-cli/auth): Full interface and status codes

## Frequently asked questions

### Which claims must my JWT contain?

Every token needs `exp` (expiration) and `user_id` claims. If you set JWT_ISSUER or JWT_AUDIENCE, the token must also carry matching `iss` or `aud` claims. A token without `user_id` is rejected with status 401, code `INVALID_TOKEN`.

### Why do I get 401 with code INVALID_TOKEN and no token?

The request had no Authorization header, or it was not a Bearer credential. Send `Authorization: Bearer <token>` on every HTTP request, or use the `10xgraph-bearer` subprotocol on WebSocket.

### Does a role with reach all let an admin run inside another user's thread?

No. Reach `tenant` and `all` widen reads, lists, deletes and stop. Runs and state or message writes always stay on the caller's own threads, admins included.

### What happens when I ask for another user's thread?

The server answers 404, the same as for a thread that does not exist. Storage filters every query by the caller's reach, so a foreign thread is invisible.
