Skip to content
LangSmith 文档版本 跟随上游 源快照 3c26e647 更新于 2026-10-18

设置自定义身份验证

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

这是身份验证系列的第 1 部分:

  1. 设置自定义身份验证(你在这里)- 控制谁可以访问你的机器人
  2. 使对话私有 - 让用户拥有私密对话
  3. 连接身份验证提供程序 - 添加真实用户账户,并在生产中使用 OAuth2 进行验证

本指南假设你对以下概念有基本了解:

NOTE

自定义身份验证仅适用于 LangSmith SaaS 部署或 Enterprise 自托管部署。

1. 创建你的应用

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

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

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

bash
pip install -e .
langgraph dev
bash
uv add .
langgraph dev
bash
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.

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

No authentication: the dev server is publicly reachable, anyone can access the bot if exposed to the internet.

2. 添加身份验证

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

NOTE

在本教程中,出于示例目的,你将从一个硬编码令牌开始。你将在第三个教程中获得 “生产就绪” 的身份验证方案。

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

创建一个新文件 src/security/auth.py。你的代码将放在这里,用于检查用户是否被允许访问你的机器人:

python
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.json 配置中,告诉 LangGraph 使用身份验证:

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

3. 测试你的机器人

再次启动服务器以测试所有内容:

bash
langgraph dev --no-browser

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

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

要在 Studio 之外接受 LangSmith API 密钥(x-api-key)与自定义处理器并行使用,请设置 allow_langsmith_api_keys: true。带有 Authorization 标头的请求仍使用自定义身份验证。所有其他请求使用 LangSmith 身份验证。设置 x-auth-scheme: langsmith 标头可强制使用 LangSmith 身份验证,即使存在 Authorization。通过 LangSmith 身份验证的调用方会将 ctx.user.identity 暴露为 LangSmith 用户 ID(或缺失),并将 ctx.permissions 暴露为 ["authenticated"]。自定义 @auth.on 处理器仍会运行,因此如果两条路径应共享资源规则,请设计它们以接受该形状。此选项要求 disable_studio_auth 未设置或为 false。

NOTE

allow_langsmith_api_keys 需要 Agent Server 0.14.0rc2 或更高版本。

4. 与你的机器人聊天

现在,只有当你在请求标头中提供有效令牌时才能访问机器人。但是,在你于教程下一节添加资源授权处理器之前,用户仍然可以访问彼此的资源。

Auth gate passes requests with a valid token, but no per-resource filters are applied yet—so users share visibility until authorization handlers are added in the next step.

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

python
import asyncio

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. 查看 Auth、Auth.authenticate 和 MinimalUserDict 的 API 参考,了解更多身份验证细节。

BytesRouter 是社区翻译站点,所有译文仅供参考,一切以官方英文原文为准。