如何添加自定义身份验证¶
按部署类型支持
自定义身份验证受 托管 LangGraph 云 和 企业 自托管计划的所有部署支持。精简版 自托管计划不支持此功能。
本指南展示了如何为您的 LangGraph 平台应用程序添加自定义身份验证。本指南适用于 LangGraph Cloud、BYOC 和自托管部署。它不适用于在您自己的自定义服务器中单独使用 LangGraph 开源库的情况。
1. 实现身份验证¶
import { Auth, HTTPException } from "@langchain/langgraph-sdk/auth";
export const auth = new Auth()
.authenticate(async (request: Request) => {
const authorization = request.headers.get("authorization");
const token = authorization?.split(" ").at(-1);
try {
const userId = (await verifyToken(token)) as string;
return userId;
} catch (error) {
throw new HTTPException(401, { message: "Invalid token", cause: error });
}
})
.on("*", ({ value, user }) => {
// Add owner to the resource metadata
if ("metadata" in value) {
value.metadata ??= {};
value.metadata.owner = user.identity;
}
// Filter the resource by the owner
return { owner: user.identity };
})
.on("store", ({ user, value }) => {
if (value.namespace != null) {
// Assuming you organize information in store like (user_id, resource_type, resource_id)
const [userId, resourceType, resourceId] = value.namespace;
if (userId !== user.identity) {
throw new HTTPException(403, { message: "Not authorized" });
}
}
});
2. 更新配置¶
在您的 langgraph.json
中,添加您的身份验证文件路径
{
"node_version": "20",
"graphs": {
"agent": "./agent.mts:graph"
},
"env": ".env",
"auth": {
"path": "./auth.mts:auth"
}
}
3. 从客户端连接¶
在服务器中设置身份验证后,请求必须根据您选择的方案包含所需的授权信息。假设您正在使用 JWT 令牌身份验证,您可以通过以下任何方法访问您的部署
from langgraph.pregel.remote import RemoteGraph
my_token = "your-token" # In practice, you would generate a signed token with your auth provider
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"; // In practice, you would generate a signed token with your auth provider
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"; // In practice, you would generate a signed token with your auth provider
const remoteGraph = new RemoteGraph({
graphId: "agent",
url: "http://localhost:2024",
headers: { Authorization: `Bearer ${my_token}` },
});
const threads = await remoteGraph.invoke(...);