> ## 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.

# 添加自定义认证

本指南向您展示如何为您的 LangSmith 应用程序添加自定义认证。此页面上的步骤适用于 [云部署](/langsmith/cloud) 和 [自托管部署](/langsmith/self-hosted)。它不适用于在您自己的自定义服务器中独立使用 [LangGraph 开源库](/oss/python/langgraph/overview) 的情况。

## 为您的部署添加自定义认证

要利用自定义认证并在您的部署中访问用户级元数据，请设置自定义认证，通过自定义认证处理器自动填充 `config["configurable"]["langgraph_auth_user"]` 对象。然后，您可以在图中使用 `langgraph_auth_user` 键访问此对象，以[允许代理代表用户执行经过认证的操作](#enable-agent-authentication)。

1. 实现认证：

   <Note>
     如果没有自定义的 `@auth.authenticate` 处理器，LangGraph 只能看到 API 密钥所有者（通常是开发者），因此请求不会限定到单个最终用户。要传播自定义令牌，您必须实现自己的处理器。
   </Note>

   ```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
   from langgraph_sdk import Auth
   import requests

   auth = Auth()

   def is_valid_key(api_key: str) -> bool:
       is_valid = # 您的 API 密钥验证逻辑
       return is_valid

   @auth.authenticate # (1)!
   async def authenticate(headers: dict) -> Auth.types.MinimalUserDict:
       api_key = headers.get(b"x-api-key")
       if not api_key or not is_valid_key(api_key):
           raise Auth.exceptions.HTTPException(status_code=401, detail="Invalid API key")

       # 从您的密钥存储中获取用户特定的令牌
       user_tokens = await fetch_user_tokens(api_key)

       return { # (2)!
           "identity": api_key,  # 从 LangSmith 获取用户 ID
           "github_token" : user_tokens.github_token
           "jira_token" : user_tokens.jira_token
           # ... 此处为自定义字段/密钥
       }
   ```

* 此处理器接收请求（标头等），验证用户，并返回一个至少包含身份字段的字典。
* 您可以添加任何想要的自定义字段（例如，OAuth 令牌、角色、组织 ID 等）。

2. 在您的 [`langgraph.json`](/langsmith/application-structure#configuration-file) 文件中，添加您的认证文件路径：

   ```json highlight={7-9} theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
   {
       "dependencies": ["."],
       "graphs": {
       "agent": "./agent.py:graph"
       },
       "env": ".env",
       "auth": {
           "path": "./auth.py:my_auth"
       }
   }
   ```
3. 一旦您在服务器中设置了认证，请求必须根据您选择的方案包含所需的授权信息。假设您使用 JWT 令牌认证，您可以使用以下任何一种方法访问您的部署：

   <Tabs>
     <Tab title="Python 客户端">
       ```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
       from langgraph_sdk import get_client

       my_token = "your-token" # 实际上，您会使用您的认证提供商生成一个签名令牌
       client = get_client(
           url="http://localhost:2024",
           headers={"Authorization": f"Bearer {my_token}"}
       )
       threads = await client.threads.search()
       ```
     </Tab>

     <Tab title="Python RemoteGraph">
       ```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
       from langgraph.pregel.remote import RemoteGraph

       my_token = "your-token" # 实际上，您会使用您的认证提供商生成一个签名令牌
       remote-graph = RemoteGraph(
           "agent",
           url="http://localhost:2024",
           headers={"Authorization": f"Bearer {my_token}"}
       )
       threads = await remote-graph.ainvoke(...)
       ```
     </Tab>

     <Tab title="JavaScript 客户端">
       ```javascript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
       import { Client } from "@langchain/langgraph-sdk";

       const my_token = "your-token"; // 实际上，您会使用您的认证提供商生成一个签名令牌
       const client = new Client({
       apiUrl: "http://localhost:2024",
       defaultHeaders: { Authorization: `Bearer ${my_token}` },
       });
       const threads = await client.threads.search();
       ```
     </Tab>

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

       const my_token = "your-token"; // 实际上，您会使用您的认证提供商生成一个签名令牌
       const remoteGraph = new RemoteGraph({
       graphId: "agent",
       url: "http://localhost:2024",
       headers: { Authorization: `Bearer ${my_token}` },
       });
       const threads = await remoteGraph.invoke(...);
       ```
     </Tab>

     <Tab title="CURL">
       ```bash theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
       curl -H "Authorization: Bearer ${your-token}" http://localhost:2024/threads
       ```
     </Tab>
   </Tabs>

   有关 RemoteGraph 的更多详细信息，请参阅 [使用 RemoteGraph](/langsmith/use-remote-graph) 指南。

## 启用代理认证

在[认证](#为您的部署添加自定义认证)之后，平台会创建一个特殊的配置对象（`config`），该对象被传递给 LangSmith 部署。此对象包含有关当前用户的信息，包括您从 `@auth.authenticate` 处理器返回的任何自定义字段。

要允许代理代表用户执行经过认证的操作，请在图中使用 `langgraph_auth_user` 键访问此对象：

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
def my_node(state, config):
    user_config = config["configurable"].get("langgraph_auth_user")
    # 令牌在 @auth.authenticate 函数期间已解析
    token = user_config.get("github_token","")
    ...
```

<Note>
  从安全的密钥存储中获取用户凭据。不建议将密钥存储在图状态中。
</Note>

### 为 Studio 授权用户

默认情况下，如果您在资源上添加了自定义授权，这也将应用于从 [Studio](/langsmith/studio) 进行的交互。如果您愿意，可以通过检查 [is\_studio\_user()](https://langchain-ai.github.io/langgraph/cloud/reference/sdk/python_sdk_ref/#langgraph_sdk.auth.types.StudioUser) 来以不同方式处理已登录的 Studio 用户。

<Note>
  `is_studio_user` 在 langgraph-sdk 的 0.1.73 版本中添加。如果您使用的是较旧版本，仍然可以检查 `isinstance(ctx.user, StudioUser)`。
</Note>

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
from langgraph_sdk.auth import is_studio_user, Auth
auth = Auth()

# ... 设置 authenticate 等。

@auth.on
async def add_owner(
    ctx: Auth.types.AuthContext,
    value: dict  # 发送到此访问方法的负载
) -> dict:  # 返回一个限制资源访问的过滤器字典
    if is_studio_user(ctx.user):
        return {}

    filters = {"owner": ctx.user.identity}
    metadata = value.setdefault("metadata", {})
    metadata.update(filters)
    return filters
```

仅当您希望允许开发者访问部署在托管 LangSmith SaaS 上的图时，才使用此功能。

## 了解更多

* [认证与访问控制](/langsmith/auth)
* [设置自定义认证教程](/langsmith/set-up-custom-auth)

***

<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/custom-auth.mdx) 或 [提交问题](https://github.com/langchain-ai/docs/issues/new/choose)。
  </Callout>
</div>
