跳转至

添加自定义认证

前提条件

本指南假设你熟悉以下概念:

如需更详细的教程,请参阅 设置自定义认证 教程。

部署类型支持

自定义认证支持 托管 LangGraph Platform 中的所有部署,以及 企业版 自托管计划。

本指南展示如何向 LangGraph Platform 应用添加自定义认证。本指南适用于 LangGraph Platform 和自托管部署。不适用于在你自己的自定义服务器中单独使用 LangGraph 开源库的情况。

Note

自定义认证支持所有 托管 LangGraph Platform 部署,以及 企业版 自托管计划。

向部署添加自定义认证

要利用自定义认证并在部署中访问用户级元数据,请设置自定义认证以通过自定义认证处理器自动填充 config["configurable"]["langgraph_auth_user"] 对象。然后你可以在图中使用 langgraph_auth_user 键访问此对象,以 允许智能代理代表用户执行认证操作

  1. 实现认证:

    Note

    没有自定义 @auth.authenticate 处理器,LangGraph 只能看到 API 密钥所有者(通常是开发者),因此请求不会限定到单个最终用户。要传播自定义令牌,你必须实现自己的处理器。

    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("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
            # ... 在此添加自定义字段/密钥
        }
    
    1. 此处理器接收请求(头部等),验证用户,并返回至少包含 identity 字段的字典。
    2. 你可以添加任何你想要的自定义字段(例如 OAuth 令牌、角色、组织 ID 等)。
  2. 在你的 langgraph.json 中,添加认证文件的路径:

    {
      "dependencies": ["."],
      "graphs": {
        "agent": "./agent.py:graph"
      },
      "env": ".env",
      "auth": {
        "path": "./auth.py:my_auth"
      }
    }
    
  3. 在服务器中设置认证后,请求必须包含基于你选择的方案所需的授权信息。假设你使用 JWT 令牌认证,你可以使用以下任一方法访问你的部署:

    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()
    

    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(...)
    
    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(...)
    

    curl -H "Authorization: Bearer ${your-token}" http://localhost:2024/threads
    

启用智能代理认证

认证 后,平台会创建一个特殊的配置对象(config),该对象会传递给 LangGraph Platform 部署。此对象包含有关当前用户的信息,包括你从 @auth.authenticate 处理器返回的任何自定义字段。

要允许智能代理代表用户执行认证操作,请在图中使用 langgraph_auth_user 键访问此对象:

def my_node(state, config):
    user_config = config["configurable"].get("langgraph_auth_user")
    # 令牌在 @auth.authenticate 函数期间解析
    token = user_config.get("github_token","")
    ...

Note

从安全的密钥存储获取用户凭证。不建议将密钥存储在图状态中。

授权 Studio 用户

默认情况下,如果你在资源上添加了自定义授权,这也将适用于从 Studio 进行的交互。如果你想对已登录的 Studio 用户进行不同处理,可以检查 is_studio_user()

Note

is_studio_user 是在 langgraph-sdk 0.1.73 版本中添加的。如果你使用的是旧版本,仍然可以检查 isinstance(ctx.user, StudioUser)

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

只有当你想允许开发者访问部署在托管 LangGraph Platform SaaS 上的图时才使用此功能。

  1. 实现认证:

    Note

    没有自定义 authenticate 处理器,LangGraph 只能看到 API 密钥所有者(通常是开发者),因此请求不会限定到单个最终用户。要传播自定义令牌,你必须实现自己的处理器。

    import { Auth, HTTPException } from "@langchain/langgraph-sdk/auth";
    
    const auth = new Auth()
      .authenticate(async (request) => {
        const authorization = request.headers.get("Authorization");
        const token = authorization?.split(" ")[1]; // "Bearer <token>"
        if (!token) {
          throw new HTTPException(401, "No token provided");
        }
        try {
          const user = await verifyToken(token);
          return user;
        } catch (error) {
          throw new HTTPException(401, "Invalid token");
        }
      })
      // 添加授权规则以实际控制对资源的访问
      .on("*", async ({ user, value }) => {
        const filters = { owner: user.identity };
        const metadata = value.metadata ?? {};
        metadata.update(filters);
        return filters;
      })
      // 假设你在存储中按 (user_id, resource_type, resource_id) 组织信息
      .on("store", async ({ user, value }) => {
        const namespace = value.namespace;
        if (namespace[0] !== user.identity) {
          throw new HTTPException(403, "Not authorized");
        }
      });
    
    1. 此处理器接收请求(头部等),验证用户,并返回至少包含 identity 字段的对象。
    2. 你可以添加任何你想要的自定义字段(例如 OAuth 令牌、角色、组织 ID 等)。
  2. 在你的 langgraph.json 中,添加认证文件的路径:

    {
      "dependencies": ["."],
      "graphs": {
        "agent": "./agent.ts:graph"
      },
      "env": ".env",
      "auth": {
        "path": "./auth.ts:my_auth"
      }
    }
    
  3. 在服务器中设置认证后,请求必须包含基于你选择的方案所需的授权信息。假设你使用 JWT 令牌认证,你可以使用以下任一方法访问你的部署:

    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();
    
    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(...);
    
    curl -H "Authorization: Bearer ${your-token}" http://localhost:2024/threads
    

启用智能代理认证

认证 后,平台会创建一个特殊的配置对象(config),该对象会传递给 LangGraph Platform 部署。此对象包含有关当前用户的信息,包括你从 authenticate 处理器返回的任何自定义字段。

要允许智能代理代表用户执行认证操作,请在图中使用 langgraph_auth_user 键访问此对象:

async function myNode(state, config) {
  const userConfig = config["configurable"]["langgraph_auth_user"];
  // 令牌在 authenticate 函数期间解析
  const token = userConfig["github_token"];
  ...
}

Note

从安全的密钥存储获取用户凭证。不建议将密钥存储在图状态中。

了解更多