如何添加自定义认证¶
仅限 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
# 假设您将信息组织在存储中,如 (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令牌身份验证,您可以使用以下任意一种方法访问您的部署:
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(...);