设置自定义认证¶
在本教程中,我们将构建一个只允许特定用户访问的聊天机器人。我们将从 LangGraph 模板开始,逐步添加基于令牌的安全性。最后,你将拥有一个可用的聊天机器人,它在允许访问之前会检查有效的令牌。
这是我们认证系列的第一部分
本指南假定你对以下概念有基本了解
注意
自定义认证仅适用于 LangGraph 平台 SaaS 部署或企业自托管部署。
1. 创建你的应用¶
使用 LangGraph 入门模板创建一个新的聊天机器人
pip install -U "langgraph-cli[inmem]"
langgraph new --template=new-langgraph-project-python custom-auth
cd custom-auth
该模板为我们提供了一个占位符 LangGraph 应用。通过安装本地依赖项并运行开发服务器来试用它
服务器将启动并在浏览器中打开 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 LangGraph Platform.
如果你将其自托管到公共互联网上,任何人都可以访问它!
2. 添加认证¶
现在你已经有了一个基本的 LangGraph 应用,为其添加认证。
注意
在本教程中,你将从一个硬编码的令牌开始,仅用于示例目的。你将在第三个教程中实现“生产就绪”的认证方案。
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"
}
}
3. 测试你的机器人¶
再次启动服务器以测试所有内容
如果你没有添加 --no-browser
,Studio UI 将在浏览器中打开。你可能会问,Studio 是如何仍然连接到我们的服务器的?默认情况下,即使在使用自定义认证时,我们也允许从 LangGraph Studio 访问。这使得在 Studio 中开发和测试你的机器人变得更容易。你可以通过在认证配置中设置 disable_studio_auth: "true"
来移除此备用认证选项
4. 与你的机器人聊天¶
现在,只有在请求头中提供有效令牌,你才能访问机器人。然而,用户仍然可以访问彼此的资源,直到你在本教程的下一部分中添加资源授权处理程序。
在文件或笔记本中运行以下代码
from langgraph_sdk import get_client
# Try without a token (should fail)
client = get_client(url="https://: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="https://: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)
你应该会看到
- 没有有效令牌,我们无法访问机器人
- 使用有效令牌,我们可以创建线程并聊天
恭喜!你已经构建了一个只允许“已认证”用户访问的聊天机器人。虽然此系统尚未(或未完全)实现生产就绪的安全方案,但我们已经学习了如何控制机器人访问的基本机制。在下一个教程中,我们将学习如何为每个用户提供自己的私密对话。
下一步¶
既然你可以控制谁访问你的机器人,你可能想要