跳到内容

设置自定义身份验证(第 ⅓ 部分)

这是我们的身份验证系列的第一部分

  1. 基本身份验证(您在此处)- 控制谁可以访问您的机器人
  2. 资源授权 - 让用户拥有私密对话
  3. 生产环境身份验证 - 添加真实用户帐户并使用 OAuth2 进行验证

先决条件

本指南假定您基本熟悉以下概念

仅限 Python

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

按部署类型支持

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

在本教程中,我们将构建一个仅允许特定用户访问的聊天机器人。我们将从 LangGraph 模板开始,逐步添加基于令牌的安全性。到最后,您将拥有一个可以检查有效令牌然后允许访问的工作聊天机器人。

设置我们的项目

首先,让我们使用 LangGraph 入门模板创建一个新的聊天机器人

pip install -U "langgraph-cli[inmem]"
langgraph new --template=new-langgraph-project-python custom-auth
cd custom-auth

该模板为我们提供了一个占位符 LangGraph 应用程序。让我们通过安装本地依赖项并运行开发服务器来试用它。

pip install -e .
langgraph dev
如果一切正常,服务器应该启动并在您的浏览器中打开工作室。

此内存服务器专为开发和测试而设计。对于生产用途,请使用 LangGraph Cloud。

图应该运行,如果您将其自托管在公共互联网上,任何人都可以访问它!

No auth

现在我们已经看到了基本的 LangGraph 应用程序,让我们为其添加身份验证!

占位符令牌

在第 1 部分中,我们将从硬编码令牌开始进行说明。在掌握基础知识后,我们将在第 3 部分中介绍“生产就绪”的身份验证方案。

添加身份验证

Auth 对象允许您注册一个身份验证函数,LangGraph 平台将在每个请求上运行该函数。此函数接收每个请求并决定是否接受或拒绝。

创建一个新文件 src/security/auth.py。这是我们的代码将驻留的地方,用于检查用户是否被允许访问我们的机器人

src/security/auth.py
from langgraph_sdk import Auth

# This is our toy user database. Do not do this in production
VALID_TOKENS = {
    "user1-token": {"id": "user1", "name": "Alice"},
    "user2-token": {"id": "user2", "name": "Bob"},
}

# The "Auth" object is a container that LangGraph will use to mark our authentication function
auth = Auth()


# The `authenticate` decorator tells LangGraph to call this function as middleware
# for every request. This will determine whether the request is allowed or not
@auth.authenticate
async def get_current_user(authorization: str | None) -> Auth.types.MinimalUserDict:
    """Check if the user's token is valid."""
    assert authorization
    scheme, token = authorization.split()
    assert scheme.lower() == "bearer"
    # Check if token is valid
    if token not in VALID_TOKENS:
        raise Auth.exceptions.HTTPException(status_code=401, detail="Invalid token")

    # Return user info if valid
    user_data = VALID_TOKENS[token]
    return {
        "identity": user_data["id"],
    }

请注意,我们的 身份验证 处理程序执行两个重要操作

  1. 检查请求的 Authorization 标头 中是否提供了有效令牌
  2. 返回用户的 身份

现在告诉 LangGraph 使用我们的身份验证,方法是将以下内容添加到 langgraph.json 配置文件中

langgraph.json
{
  "dependencies": ["."],
  "graphs": {
    "agent": "./src/agent/graph.py:graph"
  },
  "env": ".env",
  "auth": {
    "path": "src/security/auth.py:auth"
  }
}

测试我们的“安全”机器人

让我们再次启动服务器以测试一切!

langgraph dev --no-browser
工作室中的自定义身份验证

如果您没有添加 --no-browser,工作室 UI 将在浏览器中打开。您可能想知道,工作室如何仍然能够连接到我们的服务器?默认情况下,即使在使用自定义身份验证时,我们也允许从 LangGraph 工作室进行访问。这使得在工作室中开发和测试您的机器人变得更加容易。您可以通过在身份验证配置中设置 disable_studio_auth: "true" 来删除此备用身份验证选项

{
    "auth": {
        "path": "src/security/auth.py:auth",
        "disable_studio_auth": "true"
    }
}

现在让我们尝试与我们的机器人聊天。如果我们正确地实现了身份验证,则只有在请求标头中提供有效令牌时,我们才能访问该机器人。但是,在我们在本教程的下一节中添加资源授权处理程序之前,用户仍然可以访问彼此的资源。

Authentication, no authorization handlers

在文件或笔记本中运行以下代码

from langgraph_sdk import get_client

# Try without a token (should fail)
client = get_client(url="http://localhost:2024")
try:
    thread = await client.threads.create()
    print("❌ Should have failed without token!")
except Exception as e:
    print("✅ Correctly blocked access:", e)

# Try with a valid token
client = get_client(
    url="http://localhost:2024", headers={"Authorization": "Bearer user1-token"}
)

# Create a thread and chat
thread = await client.threads.create()
print(f"✅ Created thread as Alice: {thread['thread_id']}")

response = await client.runs.create(
    thread_id=thread["thread_id"],
    assistant_id="agent",
    input={"messages": [{"role": "user", "content": "Hello!"}]},
)
print("✅ Bot responded:")
print(response)

您应该看到

  1. 没有有效令牌,我们无法访问机器人
  2. 使用有效令牌,我们可以创建线程和聊天

恭喜!您已经构建了一个仅允许“已验证身份”的用户访问的聊天机器人。虽然此系统(尚未)实现生产就绪的安全方案,但我们已经了解了如何控制对我们机器人的访问的基本机制。在下一个教程中,我们将学习如何为每个用户提供他们自己的私密对话。

下一步是什么?

现在您可以控制谁访问您的机器人,您可能想要

  1. 继续本教程,转到使对话私密化(第 ⅔ 部分),了解资源授权。
  2. 阅读有关身份验证概念的更多信息。
  3. 查看API 参考以获取更多身份验证详细信息。

评论