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

# 设置代理认证（Beta 版）

> 使用代理认证，通过 OAuth 2.0 凭证实现从代理到任何系统的安全访问。

<Note>代理认证目前处于 **Beta** 版本，正在积极开发中。如需提供反馈或使用此功能，请联系 [LangChain 团队](https://forum.langchain.com/c/help/langsmith/)。</Note>

## 安装

<Tabs>
  <Tab title="Python">
    <CodeGroup>
      ```bash pip theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
      pip install langchain-auth
      ```

      ```bash uv theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
      uv add langchain-auth
      ```
    </CodeGroup>
  </Tab>

  <Tab title="JavaScript">
    ```bash theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
    npm install @langchain/auth
    ```
  </Tab>
</Tabs>

## 快速开始

### 1. 初始化客户端

<Tabs>
  <Tab title="Python">
    ```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
    from langchain_auth import Client

    client = Client(api_key="your-langsmith-api-key")
    ```
  </Tab>

  <Tab title="JavaScript">
    ```javascript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
    import { Client } from '@langchain/auth';

    const client = new Client({ apiKey: 'your-langsmith-api-key' });
    ```
  </Tab>
</Tabs>

#### 自托管配置

对于自托管的 LangSmith 实例，请使用实例上的 `/api-host` 路径指定 API URL。

<Tabs>
  <Tab title="环境变量">
    ```bash theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
    export LANGSMITH_API_URL="https://your-langsmith-instance.com/api-host"
    ```

    然后正常初始化客户端：

    ```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
    client = Client(api_key="your-langsmith-api-key")
    ```
  </Tab>

  <Tab title="显式配置 (Python)">
    ```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
    client = Client(
        api_key="your-langsmith-api-key",
        api_url="https://your-langsmith-instance.com/api-host"
    )
    ```
  </Tab>

  <Tab title="显式配置 (JavaScript)">
    ```javascript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
    const client = new Client({
        apiKey: 'your-langsmith-api-key',
        apiUrl: 'https://your-langsmith-instance.com/api-host'
    });
    ```
  </Tab>
</Tabs>

### 2. 设置 OAuth 提供方

在代理能够进行身份验证之前，您需要按照以下流程配置一个 OAuth 提供方：

1. 为您的 OAuth 提供方选择一个在 LangChain 平台中使用的唯一标识符（例如，"github-local-dev"、"google-workspace-prod"）。

2. 转到您的 OAuth 提供方的开发者控制台，并创建一个新的 OAuth 应用程序。

3. 在您的 OAuth 提供方中设置回调 URL：

<Tabs>
  <Tab title="LangSmith Cloud">
    ```
    https://smith.langchain.com/host-oauth-callback/{provider_id}
    ```

    例如，如果您的 provider\_id 是 "github-local-dev"，请使用：

    ```
    https://smith.langchain.com/host-oauth-callback/github-local-dev
    ```
  </Tab>

  <Tab title="自托管">
    ```
    https://{your-langsmith-instance}/host-oauth-callback/{provider_id}
    ```

    例如，如果您的实例是 `langsmith.example.com` 且 provider\_id 是 "github"，请使用：

    ```
    https://langsmith.example.com/host-oauth-callback/github
    ```
  </Tab>
</Tabs>

4. 使用 `client.create_oauth_provider()` 并传入您 OAuth 应用的凭证：

<Tabs>
  <Tab title="Python">
    ```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
    new_provider = await client.create_oauth_provider(
        provider_id="{provider_id}",  # 提供任意唯一 ID
        name="{provider_display_name}",  # 提供任意显示名称
        client_id="{your_client_id}",
        client_secret="{your_client_secret}",
        auth_url="{auth_url_of_your_provider}",
        token_url="{token_url_of_your_provider}",
    )
    ```
  </Tab>

  <Tab title="JavaScript">
    ```javascript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
    const newProvider = await client.createOAuthProvider({
        providerId: '{provider_id}',  // 提供任意唯一 ID
        name: '{provider_display_name}',  // 提供任意显示名称
        clientId: '{your_client_id}',
        clientSecret: '{your_client_secret}',
        authUrl: '{auth_url_of_your_provider}',
        tokenUrl: '{token_url_of_your_provider}',
    });
    ```
  </Tab>
</Tabs>

### 3. 从代理进行身份验证

客户端 `authenticate()` API 用于从预配置的提供方获取 OAuth 令牌。在首次调用时，它会引导调用者完成 OAuth 2.0 认证流程。

#### 在 LangGraph 上下文中

默认情况下，令牌的作用域通过 Assistant ID 参数限定到调用代理。

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
auth_result = await client.authenticate(
    provider="{provider_id}",
    scopes=["scopeA"],
    user_id="your_user_id"  # 任何用于将此令牌限定到人类调用者的唯一标识符
)

# 或者显式指定 agent_id 以获取代理作用域的令牌
auth_result = await client.authenticate(
    provider="{provider_id}",
    scopes=["scopeA"],
    user_id="your_user_id",
    agent_id="specific-agent-id"  # 可选：显式设置代理作用域
)
```

在执行过程中，如果需要身份验证，SDK 将抛出一个 [中断](https://langchain-ai.github.io/langgraph/how-tos/human_in_the_loop/add-human-in-the-loop/#pause-using-interrupt)。代理执行暂停，并向用户展示 OAuth URL：

<Frame caption="显示 OAuth URL 的 Studio 中断">
  <img src="https://mintcdn.com/other-405835d4/zfoblcQReEYa-is2/images/langgraph-auth-interrupt.png?fit=max&auto=format&n=zfoblcQReEYa-is2&q=85&s=ebdae9fb831df3e1dec9a8c5ddfd6897" width="1197" height="530" data-path="images/langgraph-auth-interrupt.png" />
</Frame>

用户完成 OAuth 认证并收到提供方的回调后，他们将看到认证成功页面。

<Frame caption="GitHub OAuth 成功页面">
  <img src="https://mintcdn.com/other-405835d4/zfoblcQReEYa-is2/images/github-auth-success.png?fit=max&auto=format&n=zfoblcQReEYa-is2&q=85&s=737d106447467e71c815143864091994" width="447" height="279" data-path="images/github-auth-success.png" />
</Frame>

然后代理从暂停点恢复执行，该令牌可用于任何 API 调用。我们存储并刷新 OAuth 令牌，以便用户或代理未来使用该服务时无需再次进行 OAuth 流程。

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
token = auth_result.token
```

#### 在 LangGraph 上下文之外

向用户提供 `auth_url` 以进行带外 OAuth 流程。

<Tabs>
  <Tab title="Python">
    ```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
    auth_result = await client.authenticate(
        provider="{provider_id}",
        scopes=["scopeA"],
        user_id="your_user_id"
    )

    if auth_result.status == "pending":
        print(f"请在以下地址完成 OAuth: {auth_result.url}")
        # 等待用户完成 OAuth
        completed_auth = await client.wait_for_completion(auth_result.auth_id)
        print("身份验证已完成！")
    else:
        token = auth_result.token
        print(f"已通过身份验证，令牌: {token}")
    ```
  </Tab>

  <Tab title="JavaScript">
    ```javascript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
    const authResult = await client.authenticate({
        provider: '{provider_id}',
        scopes: ['scopeA'],
        userId: 'your_user_id'
    });

    if (authResult.status === 'pending') {
        console.log(`请在以下地址完成 OAuth: ${authResult.authUrl}`);
        // 等待用户完成 OAuth
        const completedAuth = await client.waitForCompletion(authResult.authId);
        console.log('身份验证已完成！');
    } else {
        const token = authResult.token;
        console.log(`已通过身份验证，令牌: ${token}`);
    }
    ```
  </Tab>
</Tabs>

## 故障排除

### 自托管：405 方法不允许

如果您收到 `405 Method Not Allowed` 错误，请确保 `LANGSMITH_API_URL` 指向 `/api-host` 路径：

```bash theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
export LANGSMITH_API_URL="https://your-instance.com/api-host"
```

### 自托管：OAuth 回调 URL 格式错误

确保您的 OAuth 提供方的重定向 URI 与您的 LangSmith 实例 URL 匹配：

```
https://your-instance.com/host-oauth-callback/{provider_id}
```

***

<div className="source-links">
  <Callout icon="terminal-2">
    [将这些文档](/use-these-docs) 通过 MCP 连接到 Claude、VSCode 等，以获取实时答案。
  </Callout>

  <Callout icon="edit">
    [在 GitHub 上编辑此页面](https://github.com/langchain-ai/docs/edit/main/src/langsmith/agent-auth.mdx) 或 [提交问题](https://github.com/langchain-ai/docs/issues/new/choose)。
  </Callout>
</div>
