如何添加自定义身份验证¶
按部署类型支持
托管式 LangGraph 云中的所有部署以及企业版自托管计划都支持自定义身份验证。精简版自托管计划不支持此功能。
本指南介绍了如何将自定义身份验证添加到您的 LangGraph 平台应用程序。本指南适用于 LangGraph 云、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 令牌身份验证,您可以使用以下任何方法访问您的部署:
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: "https://: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: "https://:2024",
headers: { Authorization: `Bearer ${my_token}` },
});
const threads = await remoteGraph.invoke(...);
授权 Studio 用户¶
默认情况下,如果您在资源上添加自定义授权,这也将适用于从 Studio 进行的交互。如果您愿意,可以使用 isStudioUser() 以特殊方式处理已登录的 Studio 用户。
import { Auth, isStudioUser } from "@langchain/langgraph-sdk/auth";
export const auth = new Auth().on("*", ({ value, user }) => {
// If the request is made using LangSmith API-key auth
if (isStudioUser(user)) {
// E.g., allow all requests
return {};
}
// Otherwise, apply regular authorization logic ...
if ("metadata" in value) {
value.metadata ??= {};
value.metadata.owner = user.identity;
}
// Filter the resource by the owner
return { owner: user.identity };
});
仅当您希望允许开发者访问部署在托管式 LangGraph 平台 SaaS 上的图时,才使用此功能。