Skip to content

如何添加自定义身份验证

前提条件

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

如需更详细的分步指南,请参阅 设置自定义身份验证 教程。

仅适用于 Python

目前,我们仅支持在使用 langgraph-api>=0.0.11 的 Python 部署中进行自定义身份验证和授权。不久后将添加对 LangGraph.JS 的支持。

按部署类型提供的支持

托管的 LangGraph 云**以及 **企业版 自托管计划中的所有部署均支持自定义身份验证。精简版 自托管计划不支持。

本指南介绍了如何为你的 LangGraph 平台应用程序添加自定义身份验证。本指南适用于 LangGraph 云、自带云(BYOC)和自托管部署。不适用于在你自己的自定义服务器中单独使用 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

# 假设你在存储中按照 (用户 ID, 资源类型, 资源 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",
  headers: { 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

Comments