跳到内容

如何添加自定义身份验证

先决条件

本指南假设您熟悉以下概念

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

仅限 Python

我们目前仅在 langgraph-api>=0.0.11 的 Python 部署中支持自定义身份验证和授权。LangGraph.JS 的支持即将添加。

按部署类型支持

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

本指南介绍如何向您的 LangGraph 平台应用程序添加自定义身份验证。本指南适用于 LangGraph Cloud、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:
        # Verify token with your auth provider
        user_id = await verify_token(token)
        return user_id
    except Exception:
        raise Auth.exceptions.HTTPException(
            status_code=401,
            detail="Invalid token"
        )

# Add authorization rules to actually control access to resources
@my_auth.on
async def add_owner(
    ctx: Auth.types.AuthContext,
    value: dict,
):
    """Add owner to resource metadata and filter by owner."""
    filters = {"owner": ctx.user.identity}
    metadata = value.setdefault("metadata", {})
    metadata.update(filters)
    return filters

# Assumes you organize information in store like (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, "Not authorized"

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" # In practice, you would generate a signed token with your auth provider
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" # 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(...);
curl -H "Authorization: Bearer ${your-token}" http://localhost:2024/threads

评论