以编程方式使用文档

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

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

  1. 设置自定义身份验证(您在此处)- 控制谁可以访问您的机器人
  2. 使对话私密化 - 让用户进行私密对话
  3. 连接身份验证提供者 - 添加真实用户账户并使用 OAuth2 进行生产环境验证

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

1. 创建您的应用

使用 LangGraph 入门模板创建一个新的聊天机器人:

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

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

pip install -e .
langgraph dev
uv add .
langgraph dev
npx @langchain/langgraph-cli dev

服务器将启动并在 Studio 中打开您的浏览器:

> - 🚀 API: http://127.0.0.1:2024
> - 🎨 Studio UI: https://smith.langchain.com/studio/?baseUrl=http://127.0.0.1:2024
> - 📚 API Docs: http://127.0.0.1:2024/docs
>
> This in-memory server is designed for development and testing.
> For production use, please use LangSmith.

如果您将其自托管在公共互联网上,任何人都可以访问它。

!无身份验证:开发服务器可公开访问,如果暴露在互联网上,任何人都可以访问机器人。

2. 添加身份验证

现在你已有了一个基础的 LangGraph 应用,向其中添加身份验证。

Auth 对象允许你注册一个身份验证函数,LangSmith 部署会在每个请求上运行此函数。该函数接收每个请求并决定是接受还是拒绝。

创建一个新文件 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"],
    }

注意,你的 Auth.authenticate 处理器执行两个重要操作:

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

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

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

3. 测试您的机器人

再次启动服务器以测试所有功能:

langgraph dev --no-browser

如果您没有添加 --no-browser,Studio UI 将在浏览器中打开。默认情况下,我们也允许从 Studio 访问,即使使用自定义身份验证。这样可以更轻松地在 Studio 中开发和测试您的机器人。您可以通过设置来移除此替代身份验证选项 disable_studio_auth: true 在您的身份验证配置中:

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

4. 与您的机器人聊天

现在您应该只能通过在请求头中提供有效令牌来访问机器人。但是,在添加 资源授权处理器 之前,用户仍然可以访问彼此的资源,请参阅教程的下一节。

!Auth 门禁会让持有有效令牌的请求通过,但尚未应用每个资源的过滤器——因此用户会共享可见性,直到在下一步中添加授权处理器。

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

from langgraph_sdk import get_client


async def main():
    # 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)


if __name__ == "__main__":
    asyncio.run(main())

您应该会看到:

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

恭喜!您已经构建了一个只允许“已认证”用户访问的聊天机器人。虽然该系统(目前)尚未实现生产级别的安全方案,但我们已经学习了如何控制机器人访问权限的基本机制。在下一个教程中,我们将学习如何为每个用户提供私密的对话空间。

后续步骤

既然您已经能够控制谁可以访问您的机器人,您可能想要:

  1. 继续学习教程,请前往 让对话变得私密 来学习资源授权相关内容。
  2. 了解更多关于 认证概念.
  3. 查阅 AuthAuth.authenticateMinimalUserDict 的 API 参考,了解更多认证详情。