跳到内容

设置自定义身份验证

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

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

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

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

注意

自定义身份验证仅适用于 LangGraph Platform SaaS 部署或企业自托管部署。

1. 创建你的应用

使用 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

服务器将启动并在你的浏览器中打开工作室

> - 🚀 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 LangGraph Platform.

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

No auth

2. 添加身份验证

现在你已经有了一个基本的 LangGraph 应用,为其添加身份验证。

注意

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

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.json 配置中来告诉 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,工作室 UI 将在浏览器中打开。你可能会想,工作室是如何仍然能够连接到我们的服务器的?默认情况下,即使在使用自定义身份验证时,我们也允许从 LangGraph 工作室进行访问。这使得在工作室中开发和测试你的机器人变得更容易。你可以通过在身份验证配置中设置 disable_studio_auth: "true" 来删除此替代身份验证选项

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

4. 与你的机器人聊天

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

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 参考以获取更多身份验证详细信息。