如何添加自定义认证¶
按部署类型支持
自定义认证适用于所有在**托管 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(...);