> ## Documentation Index
> Fetch the complete documentation index at: https://docs.langchain.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Build a verify page for connect links

> Verify that the intended user is signed in to your app before they connect an OAuth account through Tool Gateway.

> [!NOTE]
>
> Tool Gateway is in [beta](https://docs.langchain.com/langsmith/release-stages.md).

An OAuth connect link lets a user sign in to a provider and connect their account. A verify page checks that the person signed in to your app is the intended user before sending them to the provider. If someone else opens a forwarded or leaked link, they cannot connect an account in that user's place.

[Agent Auth](https://docs.langchain.com/langsmith/agent-auth.md) stores the provider accounts that your users connect for [Tool Gateway](https://docs.langchain.com/langsmith/tool-gateway.md) calls, such as their Google or GitHub accounts.

## Who needs a verify page

Only OAuth connect links for the following users can use a verify page:

* **Users identified by your backend**: Your backend calls with a service key and identifies the user in [`X-LangSmith-Identity`](https://docs.langchain.com/langsmith/tool-gateway-identity#name-the-user-from-your-backend).
* **Users of your identity provider**: The call carries the user's access token from the [identity provider linked to the workspace](https://docs.langchain.com/langsmith/tool-gateway-identity.md#link-your-identity-provider).

When one of these users calls an OAuth server they have not connected, the call returns a connect link. See [When the caller is a user](https://docs.langchain.com/langsmith/tool-gateway-call-tools.md#when-the-caller-is-a-user).

Links that prompt for an API key skip the verify page. Users who have a LangSmith login sign in to LangSmith instead of visiting your verify page.

## How a connect link works

An eligible OAuth connect link opens a LangSmith page that shows the provider and the intended user. Opening the page does not use the link, so chat previews do not consume it. Only the first browser to click **Continue** can finish the sign-in.

What happens next depends on whether the workspace has a verify page:

* **Without a verify page**: The browser goes straight to the provider. If someone else uses the link and signs in, LangSmith links their provider account to the intended user. Tool calls for that user then use the wrong account.
* **With a verify page**: The browser goes to your verify page. Your app identifies the signed-in user and asks LangSmith to confirm that they are the intended user. Only after confirmation does the browser continue to the provider.

The authorization session behind a connect link expires 10 minutes after LangSmith creates it.

## Set the verify page

Each workspace has one verify page URL. Viewing the setting in the UI requires the `workspaces:read` and `workspaces:credentials:read-metadata` permissions. Changing or removing the URL also requires the `workspaces:credentials:manage` permission.

The URL must be an absolute `https` URL of up to 2048 bytes. It cannot contain user info, a fragment, or a `session_id` query parameter. LangSmith preserves any other query parameters when it redirects to your page.

> [tab] UI
>
> To configure the verify page in LangSmith:
>
> 1. Go to **Settings** > **Workspace**, and select **Agent Connections** under **Integrations**.
> 2. Open the **Connect Links** tab.
> 3. In the **Verify Page** row, click **Set up**.
> 4. In the **Set Up Verify Page** dialog, enter the **Verify Page URL**, then click **Save verify page**.
>
> The row then shows the URL. To change it, click **Edit**. To remove it, click **Edit**, click **Remove**, and confirm.

> [tab] API
>
> Send the URL to `PUT /v1/agent-auth/settings` with an API key that has the `workspaces:credentials:manage` permission:
>
> ```bash theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
> curl -sS -X PUT "$LANGSMITH_ENDPOINT/v1/agent-auth/settings" \
>   -H "X-Api-Key: $LANGSMITH_API_KEY" \
>   -H "X-Tenant-Id: $LANGSMITH_WORKSPACE_ID" \
>   -H "Content-Type: application/json" \
>   -d '{"connect_link_verify_url": "https://app.example.com/agent-auth/verify"}'
> ```
>
> The API returns `400` if the URL does not meet these requirements. To remove the verify page, set `connect_link_verify_url` to `null` or an empty string.
>
> To read the setting, send `GET /v1/agent-auth/settings`, which requires the `workspaces:credentials:read-metadata` permission. When a verify page is set, the response is:
>
> ```json theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
> {
>   "connect_link_verify_url": "https://app.example.com/agent-auth/verify"
> }
> ```
>
> The response omits `connect_link_verify_url` when no verify page is set.

## Build the verify page

When the user clicks **Continue**, LangSmith sends a `303` redirect to your verify page with `session_id=<uuid>` in the query string. In your verify page handler:

1. Read `session_id` and reject it if it is not a UUID.
2. Identify the user signed in to your app. If no one is signed in, prompt the user to sign in, then return them to the verify page with the original query string.
3. From your backend, [confirm the user](#confirm-the-signed-in-user) with LangSmith.
4. [Act on the response](#act-on-the-response): redirect the browser to the LangSmith resume URL or show an error.

If the session expires before your page confirms it, the confirmation request returns `409`, and the user needs a new link.

### Confirm the signed-in user

Send `POST /v1/agent-auth/oauth-authorization-sessions/<session-id>/confirmation` with no body and these headers:

* **`X-Api-Key`**: A service key with the `workspaces:credentials:use` or `agent-auth-credentials:use` permission.
* **`X-Tenant-Id`**: The workspace ID.
* **The signed-in user**: `X-LangSmith-Identity` or `X-Agent-Auth-Principal-Authorization`, as the following examples show.

> [!WARNING]
>
> Send the confirmation request from your backend. It carries your service key, which must stay on servers you control.

To identify the user from your backend, send `X-LangSmith-Identity` with the same value your backend sends on Tool Gateway calls for that user, or the user's principal ID:

```http theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
POST /v1/agent-auth/oauth-authorization-sessions/<session-id>/confirmation
X-Api-Key: <service-key>
X-Tenant-Id: <workspace-id>
X-LangSmith-Identity: <provider>:<user-id>
```

For a user of your linked identity provider, send the user's access token in `X-Agent-Auth-Principal-Authorization` instead:

```http theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
POST /v1/agent-auth/oauth-authorization-sessions/<session-id>/confirmation
X-Api-Key: <service-key>
X-Tenant-Id: <workspace-id>
X-Agent-Auth-Principal-Authorization: Bearer <user-access-token>
```

This header name differs from the `Authorization` header that carries the same token on Tool Gateway calls.

### Act on the response

The confirmation status determines what your page does next:

| Status | Meaning | What your page does |
| - | - | - |
| `200` | The signed-in user matches the intended user. The body is `{"url": "<url>"}`. | Redirect the browser to `url` with a `303`. |
| `403` | Someone else is signed in to your app, Agent Auth does not know the user you named, or the key lacks permission. | If `detail` is `the user is not the session's owner`, tell the user the link belongs to someone else. See [Handle a user mismatch](#handle-a-user-mismatch). Otherwise, show a generic error. |
| Any other status | The request is malformed, or the session cannot be confirmed. | Show a generic error. See [Troubleshoot](#troubleshoot). |

The returned `url` is a single-use LangSmith resume URL, not the provider sign-in URL. It starts provider sign-in only in the browser that clicked **Continue**. Error responses use problem details JSON. The `detail` field describes the error.

### Example

Add the verify route to your app server using [Starlette](https://starlette.dev/) for Python or [Hono](https://hono.dev/) for TypeScript. Both examples read these environment variables:

* **`LANGSMITH_ENDPOINT`**: The LangSmith API URL for your region, such as `https://api.smith.langchain.com`. See [Base URL](https://docs.langchain.com/langsmith/tool-gateway-api-ref.md#base-url).
* **`LANGSMITH_API_KEY`**: The service key for the confirmation request.
* **`LANGSMITH_WORKSPACE_ID`**: The workspace ID.

The example identifies the user as `myapp:<user-id>`. Replace `myapp` with the prefix your backend sends on Tool Gateway calls. For users of your identity provider, send `X-Agent-Auth-Principal-Authorization` with the user's access token instead of `X-LangSmith-Identity`.

> [!WARNING]
>
> Before using this route in your app, replace `get_signed_in_user` (`getSignedInUser` in TypeScript) with a lookup that verifies your app's authenticated session. The demo reads an unverified cookie. Do not use that cookie as proof of identity.

```python Python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
import os
from urllib.parse import urlencode
from uuid import UUID

import httpx
from starlette.applications import Starlette
from starlette.requests import Request
from starlette.responses import HTMLResponse, RedirectResponse, Response
from starlette.routing import Route

LANGSMITH_ENDPOINT = os.environ["LANGSMITH_ENDPOINT"]
LANGSMITH_API_KEY = os.environ["LANGSMITH_API_KEY"]
LANGSMITH_WORKSPACE_ID = os.environ["LANGSMITH_WORKSPACE_ID"]


def get_signed_in_user(request: Request) -> str | None:
    # Stand-in for your app's session lookup. Never trust a raw cookie like this.
    return request.cookies.get("demo_user")


async def verify(request: Request) -> Response:
    try:
        session_id = UUID(request.query_params.get("session_id", ""))
    except ValueError:
        return HTMLResponse("This link is not valid.", status_code=400)

    user_id = get_signed_in_user(request)
    if user_id is None:
        next_url = f"{request.url.path}?{request.url.query}"
        return RedirectResponse(
            f"/sign-in?{urlencode({'next': next_url})}", status_code=303
        )

    async with httpx.AsyncClient() as client:
        response = await client.post(
            f"{LANGSMITH_ENDPOINT}/v1/agent-auth/oauth-authorization-sessions/"
            f"{session_id}/confirmation",
            headers={
                "X-Api-Key": LANGSMITH_API_KEY,
                "X-Tenant-Id": LANGSMITH_WORKSPACE_ID,
                "X-LangSmith-Identity": f"myapp:{user_id}",
            },
        )

    if response.status_code == 200:
        return RedirectResponse(response.json()["url"], status_code=303)
    if (
        response.status_code == 403
        and response.json().get("detail") == "the user is not the session's owner"
    ):
        return HTMLResponse(
            "This link belongs to someone else. Ask for your own link to connect "
            "your account.",
            status_code=403,
        )
    return HTMLResponse(
        "Something went wrong. Ask for a new link and try again.", status_code=502
    )


app = Starlette(routes=[Route("/agent-auth/verify", verify)])
```

```ts TypeScript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
import { Hono, type Context } from "hono";
import { getCookie } from "hono/cookie";

const LANGSMITH_ENDPOINT = process.env.LANGSMITH_ENDPOINT!;
const LANGSMITH_API_KEY = process.env.LANGSMITH_API_KEY!;
const LANGSMITH_WORKSPACE_ID = process.env.LANGSMITH_WORKSPACE_ID!;
const UUID_PATTERN =
  /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;

function getSignedInUser(c: Context): string | undefined {
  // Stand-in for your app's session lookup. Never trust a raw cookie like this.
  return getCookie(c, "demo_user");
}

const app = new Hono();

app.get("/agent-auth/verify", async (c) => {
  const sessionId = c.req.query("session_id") ?? "";
  if (!UUID_PATTERN.test(sessionId)) {
    return c.html("This link is not valid.", 400);
  }

  const userId = getSignedInUser(c);
  if (userId === undefined) {
    const { pathname, search } = new URL(c.req.url);
    const next = new URLSearchParams({ next: pathname + search });
    return c.redirect(`/sign-in?${next}`, 303);
  }

  const response = await fetch(
    `${LANGSMITH_ENDPOINT}/v1/agent-auth/oauth-authorization-sessions/` +
      `${sessionId}/confirmation`,
    {
      method: "POST",
      headers: {
        "X-Api-Key": LANGSMITH_API_KEY,
        "X-Tenant-Id": LANGSMITH_WORKSPACE_ID,
        "X-LangSmith-Identity": `myapp:${userId}`,
      },
    },
  );

  if (response.status === 200) {
    const { url } = (await response.json()) as { url: string };
    return c.redirect(url, 303);
  }
  if (response.status === 403) {
    const { detail } = (await response.json()) as { detail?: string };
    if (detail === "the user is not the session's owner") {
      return c.html(
        "This link belongs to someone else. Ask for your own link to connect your account.",
        403,
      );
    }
  }
  return c.html("Something went wrong. Ask for a new link and try again.", 502);
});
```

## Handle a user mismatch

If the signed-in user does not match the intended user, or Agent Auth does not recognize the identity you sent, the confirmation request returns `403`. The `detail` is `the user is not the session's owner`. LangSmith stops the flow before provider sign-in and marks the session as failed with `error_code` set to `user_mismatch`.

Tell the user that the link belongs to someone else. Do not offer to retry the failed session. Get a new connect link for the intended user the same way your app got the first one.

To check for a mismatch from your backend, send `GET /v1/agent-auth/oauth-authorization-sessions/<session-id>` using the `session_id` from the verify page. Reading a user-owned session requires `workspaces:read` or `workspaces:credentials:read-metadata`. If you send an identity provider token, it must match the session owner. Check whether `error_code` is `user_mismatch`.

## Troubleshoot

The confirmation request returns these errors:

| Status | Cause | What to do |
| - | - | - |
| `400` | The request does not identify a user. The `detail` is `the signed-in user is required`. | Send `X-LangSmith-Identity` or `X-Agent-Auth-Principal-Authorization`. |
| `400` | `X-LangSmith-Identity` is not `provider:user-id` or a principal ID. | Fix the header value. |
| `403` | The key has neither `workspaces:credentials:use` nor `agent-auth-credentials:use`. The `detail` starts with `confirming a connect link requires`. | Use a service key with one of those permissions. |
| `403` | The signed-in user is not the link's user, or Agent Auth does not know the identity. The `detail` is `the user is not the session's owner`. | See [Handle a user mismatch](#handle-a-user-mismatch). If the right user is signed in, check that the identity matches the value your backend sends on Tool Gateway calls, then get a new link. |
| `404` | The session does not exist in this workspace. | Check that `X-Tenant-Id` names the workspace that issued the link, and that your page passes `session_id` through unchanged. |
| `409` | The session is not waiting for confirmation. For example, the user has not clicked **Continue**, or the session failed or expired. The `detail` is `OAuth authorization session is not waiting for confirmation`. | The user needs a new link. |

LangSmith also shows errors on its own pages:

* **The link does not work (`404`)**: Check that the user opened the full link. If it still does not work, ask for a new link.
* **The link expired or was already used (`410`)**: The user needs a new link.
* **The link was continued in another browser (`409`)**: Finish in the browser that clicked **Continue**, or ask for a new link.

## See also

* [Act as users and agents](https://docs.langchain.com/langsmith/tool-gateway-identity.md)
* [Call tools through Tool Gateway](https://docs.langchain.com/langsmith/tool-gateway-call-tools.md)
* [Connect accounts](https://docs.langchain.com/langsmith/tool-gateway-connect-accounts.md)
* [How Tool Gateway works](https://docs.langchain.com/langsmith/tool-gateway-how-it-works.md)

***

[Connect these docs](https://docs.langchain.com/use-these-docs.md) to your agent of choice via MCP for real-time answers.

[Edit this page on GitHub](https://github.com/langchain-ai/docs/edit/main/src/langsmith/agent-auth-verify-page.mdx) or [file an issue](https://github.com/langchain-ai/docs/issues/new/choose).
