# Authentication

> Pass user auth context from your frontend to the agent so it can scope tools, data, and decisions to the signed-in user.

> **Not available for agent-spec yet.** The code on this page comes from the showcase's `auth` demo, and agent-spec doesn't have it yet. See this page for [CopilotKit's Built-in Agent](/auth), [LangGraph (Python)](/langgraph-python/auth), [LangGraph (TypeScript)](/langgraph-typescript/auth).

You have a chat surface or a hook driving an agent and you want every agent run to know *who* the request came from. By the end of this guide, your frontend will forward a token, and your backend will verify it before any agent code runs. If several users share one deployment, [Thread authorization](#thread-authorization) shows how to keep each user in their own threads.

## When to use this [#when-to-use-this]

- **Multi-tenant apps** where the agent reads or writes per-user data.
- **Tool gating** where some tools should only run for authorised users.
- **Audit and billing** where every run needs an identity to attribute it to.
- **Session-aware UX** where the agent's behaviour depends on the user's role or permissions.

If you run the TypeScript runtime without Intelligence and do not need any of those, your agent can run anonymously. Intelligence runtimes require a trusted application-user identity for protected web requests.

<Callout type="info" title="Runtime authentication APIs">
The runtime hooks on this page use the TypeScript API. Python, Go, Ruby, and C#/.NET use their host's request and authentication APIs; follow their [Intelligence setup examples](/agent-spec/intelligence/quickstart#connect-your-runtime). In every language, resolve the user from a verified session or token and keep the Intelligence API key on the server.
</Callout>

## Tool gating [#tool-gating]

The most common reason to wire auth is so individual tools can decline to run. Read the resolved user inside the tool's handler and bail if the role doesn't match:

```python
def delete_record(record_id: str, *, user: User):
    if "admin" not in user.permissions:
        raise PermissionError("admin role required")
    # do the delete
```

This composes with [Human in the loop](/agent-spec/human-in-the-loop): gate on auth first, surface a confirmation card next, execute last.

## Thread authorization [#thread-authorization]

If several users share one deployment, each user must reach only their own threads. A verified token does not do this by itself. How much you build depends on your runtime:

| Runtime | Who scopes threads to a user |
| --- | --- |
| `CopilotRuntime` with `intelligence` | The runtime, via [`identifyUser`](#copilotkit-intelligence-scopes-thread-routes). |
| `CopilotRuntime` without `intelligence`, with `identifyUser` | The runtime, when the runner is `InMemoryAgentRunner` or `SqliteAgentRunner`. |
| Anything else: no `identifyUser`, a custom runner, or a custom store | You do. See [Scope threads yourself](#scope-threads-yourself). |

### CopilotKit Intelligence scopes thread routes [#copilotkit-intelligence-scopes-thread-routes]

The Intelligence runtime requires an `identifyUser` callback. Construction throws without one (or without at least one Channel). It runs on the server, once per request, and the id it returns is the scope the runtime hands to the platform. (`intelligence` below is a `CopilotKitIntelligence` instance; [Connect your runtime to Intelligence](/agent-spec/intelligence/quickstart) covers building it.)

```ts title="app/api/copilotkit/[[...slug]]/route.ts"
const runtime = new CopilotRuntime({
  agents: { default: agent },
  intelligence,
  identifyUser: async (request) => {
    const session = await verifyAppSession(request); // Your server-side auth.
    if (!session?.user) throw new Error("Unauthorized"); // Backstop; see below.

    return { id: session.user.id, name: session.user.name };
  },
});
```

<Callout type="warn" title="`identifyUser` is not an authentication gate">
  Most routes resolve the caller through `identifyUser`, but **not all of them do**. The
  ones that don't never invoke your callback at all. Rejecting unauthenticated requests is
  `onRequest`'s job: it runs before routing, on every route, without exception. Treat
  `identifyUser` as the thing that *names* an already-authenticated caller, never as the thing
  that decides whether a caller gets in.
</Callout>

Where a route does resolve the caller, what matters next is whether that id is actually *carried to the platform* as a scope:

| Route | Scoped to the resolved user? |
| --- | --- |
| `agent/run`, `agent/connect` | Yes |
| `threads/list` | Yes, and filtered by `agentId`, so `useThreads` returns the caller's threads rather than the project's |
| `threads/messages` | Yes |
| `threads/update` (rename via `PATCH`, delete via `DELETE`), `threads/archive` | Yes |
| Thread subscription token | Yes |
| `threads/events`, `threads/state` | Yes. The thread is fetched as the caller before the events or state are read |
| `agent/stop` | Yes: the thread is fetched as the caller before the run is aborted |

For everything in the Yes rows there is no ownership table to build. What you own is `identifyUser` itself:

- **Derive the id from a server-verified credential.** The callback receives the raw `Request`; whatever it returns is trusted from there on. Reading a user id straight out of a header or request body hands every caller the ability to name themselves.
- **Return a stable id.** It is the key threads hang off. If you change it (for example, by swapping an email for a subject claim), that user's existing threads stop resolving.
- **Send the `401` from `onRequest`.** Some routes, such as `transcribe` and `agent/suggest`, never call `identifyUser`. A throw in `identifyUser` returns a `500`, and a malformed id returns a `400`. Authenticate in `onRequest`, which runs on every route and can throw a `Response`. Keep the throw in `identifyUser` as a backstop.

<Callout type="warn">
  A static `identifyUser` value is suitable only for a single-user demo. In a multi-user
  application every request must resolve the authenticated user, or those users share one
  thread scope.
</Callout>

See [Scope AG-UI Streams to the signed-in user](/agent-spec/threads-lifecycle#scope-rich-threads-to-the-signed-in-user) for the full runtime contract.

### Scope threads yourself [#scope-threads-yourself]

Without `identifyUser`, the runtime has no user to bind a thread to. A `threadId` then works as a key: whoever holds it can read and continue that thread. The rest of this section is the pattern for a custom store, a plain SSE runtime, or the local in-memory runner.

The default `InMemoryAgentRunner` records an owner for each thread. Without
`identifyUser`, `GET /threads` and `POST /threads/clear` return `403`, and any
caller who holds a `threadId` can use the other
[thread routes](/agent-spec/backend/runtime-endpoints#thread-routes) to read and continue
that thread.
Anything extending it, such as `AgentCoreRunner`, inherits the same store.
`SqliteAgentRunner` does not serve them at all: its read routes answer `422`.
A runner swap is therefore a fix for durability, not for thread authorization.

#### Own the mapping [#own-the-mapping]

Whatever stores your threads, keep a record of who each one belongs to. The minimum is a table your runtime can query:

```sql
create table thread_owners (
  thread_id text primary key,
  user_id   text not null
);
create index on thread_owners (user_id);
```

Write a row when a conversation is first created. See [minting a thread with your own API](/agent-spec/threads-lifecycle#creating-a-thread-with-your-own-api-on-the-first-message) for where that hooks into the chat lifecycle.

#### Enforce it in `onBeforeHandler` [#enforce-it-in-onbeforehandler]

`onRequest` runs before routing, so it can't see which thread is being addressed. `onBeforeHandler` runs after, and receives a `route` that names the operation and (for thread-scoped routes) the `threadId`:

```ts
const handler = createCopilotRuntimeHandler({
  runtime,
  basePath: "/api/copilotkit",
  hooks: {
    onRequest: async ({ request }) => {
      // Authenticate first: reject anonymous callers outright.
      const user = await verifyRequest(request);
      if (!user) throw new Response("Unauthorized", { status: 401 });
    },

    onBeforeHandler: async ({ request, route }) => {
      const user = await verifyRequest(request);

      // Routes that name a thread directly.
      if ("threadId" in route) {
        if (!(await userOwnsThread(user.id, route.threadId))) {
          throw new Response("Forbidden", { status: 403 });
        }
        return;
      }

      // agent/run and agent/connect carry the thread in the body instead.
      if (route.method === "agent/run" || route.method === "agent/connect") {
        // Clone: the handler still needs to read the original body.
        const { threadId } = await request.clone().json();
        if (threadId && !(await userOwnsThread(user.id, threadId))) {
          throw new Response("Forbidden", { status: 403 });
        }
      }
    },
  },
});
```

The routes that carry a `threadId` on `route` are `agent/stop`, `threads/update`, `threads/archive`, `threads/messages`, `threads/events`, and `threads/state`.

<Callout type="warn" title="A thread id is not a secret">
  Treat `threadId` as a public identifier, like a database primary key in a URL. It travels
  through the browser, appears in logs, and is trivially enumerable if you mint sequential
  ids. Authorization has to be an explicit ownership check, never "they knew the id, so they
  must own it". Minting UUIDs makes guessing impractical but is not itself a control.
</Callout>

#### Filter the thread list [#filter-the-thread-list]

`threads/list` has no `threadId` to check, so `onBeforeHandler` has nothing to authorize against. Off the platform, a custom store returns exactly what you wrote. Build the list from your own ownership table instead, and drive the chat with the selected id.

Filter server-side. Hiding rows in the UI leaves the underlying route open.

`threads/clear` is the other route with no `threadId` on `route`, so the only
decision `onBeforeHandler` can make is whether to allow the call. With the
in-memory runner, the route returns `403` without `identifyUser`. With
`identifyUser`, it clears only the caller's threads. With
more than one user on the deployment, reject it unless the caller is an
operator.

<Callout type="info">
  With no platform thread store, the ownership table above *is* your thread list.
</Callout>

## Security checklist [#security-checklist]

- **Always validate** the token on the backend. Never trust the frontend's claim.
- **Scope every read and write** to the resolved user. Auth context only matters if you actually use it to filter data.
- **Authenticate in `onRequest`.** It is the only hook that runs on every route. `identifyUser` names a caller; it does not gate one, and some routes never invoke it.
- **Bind threads to a user.** On CopilotKit Intelligence that means a correct `identifyUser`. Off it, add an ownership check on every thread route rather than only at login. See [Thread authorization](#thread-authorization).
- **Use HTTPS in production.** The Bearer token is sensitive.

### Later [#later]

- **Don't log raw tokens.** Log the resolved user id (or `anonymous`) instead.
- **Refresh strategy.** Your frontend is responsible for rotating expired tokens before they reach the agent. CopilotKit doesn't refresh on your behalf.

<IntegrationGrid path="auth" />
