Skip to content

添加自定义身份验证

前提条件

本指南假定您熟悉以下概念:

如需更详细的逐步操作,请参阅 设置自定义身份验证 教程。

按部署类型的支持情况

自定义身份验证在 托管的 LangGraph 平台 中的所有部署中都得到支持,以及 企业版 的自托管计划也支持。它不支持 轻量版 的自托管计划。

本指南介绍了如何向您的 LangGraph 平台应用程序添加自定义身份验证。本指南适用于 LangGraph 平台和自托管部署。它不适用于在您自己的自定义服务器上使用 LangGraph 开源库的独立使用场景。

1. 实现身份验证

from langgraph_sdk import Auth

my_auth = Auth()

@my_auth.authenticate
async def authenticate(authorization: str) -> str:
    token = authorization.split(" ", 1)[-1] # "Bearer <token>"
    try:
        # 使用你的认证提供者验证令牌
        user_id = await verify_token(token)
        return user_id
    except Exception:
        raise Auth.exceptions.HTTPException(
            status_code=401,
            detail="无效的令牌"
        )

# 添加授权规则以实际控制对资源的访问
@my_auth.on
async def add_owner(
    ctx: Auth.types.AuthContext,
    value: dict,
):
    """向资源元数据中添加所有者并按所有者进行过滤。"""
    filters = {"owner": ctx.user.identity}
    metadata = value.setdefault("metadata", {})
    metadata.update(filters)
    return filters

# 假设你按照 (user_id, resource_type, resource_id) 的方式在存储中组织信息
@my_auth.on.store()
async def authorize_store(ctx: Auth.types.AuthContext, value: dict):
    namespace: tuple = value["namespace"]
    assert namespace[0] == ctx.user.identity, "未授权"

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