设置自定义认证 (第 ⅓ 部分)¶
仅限 Python
我们目前仅支持在 Python 部署中使用自定义认证和授权,要求 langgraph-api>=0.0.11
。对 LangGraph.JS 的支持将很快添加。
按部署类型划分的支持
托管的 LangGraph 云以及 Enterprise 自托管计划支持自定义认证。Lite 自托管计划不支持。
在本教程中,我们将构建一个只允许特定用户访问的聊天机器人。我们将从 LangGraph 模板开始,逐步添加基于令牌的安全性。完成本教程后,您将拥有一个在允许访问之前检查有效令牌的聊天机器人。
设置我们的项目¶
首先,让我们使用 LangGraph 启动模板创建一个新的聊天机器人
pip install -U "langgraph-cli[inmem]"
langgraph new --template=new-langgraph-project-python custom-auth
cd custom-auth
该模板提供了一个占位符 LangGraph 应用。让我们通过安装本地依赖项并运行开发服务器来试用它。
如果一切顺利,服务器应该启动并在您的浏览器中打开 Studio UI。
- 🚀 API: http://127.0.0.1:2024
- 🎨 Studio UI: https://smith.langchain.com/studio/?baseUrl=http://127.0.0.1:2024
- 📚 API 文档: http://127.0.0.1:2024/docs
这个内存服务器是为开发和测试而设计的。用于生产环境时,请使用 LangGraph Cloud。
图应该可以运行,如果您将其自托管到公共互联网上,任何人都可以访问它!
现在我们已经看到了基础 LangGraph 应用,让我们为其添加认证功能!
占位符令牌
在第 1 部分中,我们将以硬编码的令牌为例进行说明。掌握基础知识后,我们将在第 3 部分实现“生产环境就绪”的认证方案。
添加认证¶
Auth
对象允许您注册一个认证函数,LangGraph 平台将在每个请求上运行该函数。此函数接收每个请求并决定是接受还是拒绝。
创建一个新文件 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"],
}
注意,我们的认证处理器会执行两个重要操作
- 检查请求的 Authorization header 中是否提供了有效的令牌
- 返回用户的身份
现在通过将以下内容添加到 langgraph.json
配置中来告诉 LangGraph 使用我们的认证
{
"dependencies": ["."],
"graphs": {
"agent": "./src/agent/graph.py:graph"
},
"env": ".env",
"auth": {
"path": "src/security/auth.py:auth"
}
}
测试我们的“安全”机器人¶
让我们再次启动服务器来测试一切!
Studio UI 中的自定义认证
如果您没有添加 --no-browser
,Studio UI 将在浏览器中打开。您可能会想,Studio UI 如何仍然能够连接到我们的服务器?默认情况下,即使使用自定义认证,我们也允许从 LangGraph Studio UI 访问。这使得在 Studio UI 中开发和测试您的机器人更加容易。您可以通过在认证配置中设置 disable_studio_auth: "true"
来移除此备用认证选项。
现在让我们尝试与我们的机器人聊天。如果我们的认证实现正确,则只有在请求头中提供有效令牌时才能访问机器人。然而,在我们教程的下一部分添加资源授权处理程序之前,用户仍然可以访问彼此的资源。
在文件或笔记本中运行以下代码
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)
您应该会看到
- 没有有效令牌,我们无法访问机器人
- 有效令牌时,我们可以创建会话并聊天
恭喜!您已经构建了一个只允许“已认证”用户访问的聊天机器人。虽然这个系统尚未实现生产环境就绪的安全方案,但我们已经学会了如何控制机器人访问的基本机制。在下一个教程中,我们将学习如何为每个用户提供他们自己的私密对话。
下一步是什么?¶
现在您可以控制谁访问您的机器人了,您可能想
- 继续本教程,前往使对话私密 (第 ⅔ 部分) 了解资源授权。
- 阅读更多关于认证概念的内容。
- 查看API 参考以获取更多认证详情。