Skip to content

连接认证提供者

上一个教程中,你添加了资源授权,以让用户拥有私人的对话。然而,你仍然使用硬编码的令牌进行认证,这并不安全。现在你将用真实的用户账户替换这些令牌,并使用OAuth2

你将保留相同的 Auth 对象和资源级别的访问控制,但将认证升级为使用 Supabase 作为你的身份提供商。虽然本教程使用了 Supabase,但这些概念适用于任何 OAuth2 提供商。你将学习如何:

  1. 用真实的 JWT 令牌替换测试令牌
  2. 与 OAuth2 提供商集成以实现安全的用户认证
  3. 在保持现有授权逻辑的同时处理用户会话和元数据

背景

OAuth2 涉及三个主要角色:

  1. 授权服务器:处理用户身份验证并颁发令牌的身份提供商(例如,Supabase、Auth0、Google)
  2. 应用后端:您的 LangGraph 应用。此部分验证令牌并提供受保护的资源(对话数据)
  3. 客户端应用:用户与您的服务进行交互的网页或移动应用

标准的 OAuth2 流程大致如下:

sequenceDiagram
    participant User
    participant Client
    participant AuthServer
    participant LangGraph Backend

    User->>Client: Initiate login
    User->>AuthServer: Enter credentials
    AuthServer->>Client: Send tokens
    Client->>LangGraph Backend: Request with token
    LangGraph Backend->>AuthServer: Validate token
    AuthServer->>LangGraph Backend: Token valid
    LangGraph Backend->>Client: Serve request (e.g., run agent or graph)

先决条件

在开始本教程之前,请确保您已具备以下条件:

1. 安装依赖项

安装所需的依赖项。从您的 custom-auth 目录开始,并确保已安装 langgraph-cli

cd custom-auth
pip install -U "langgraph-cli[inmem]"

2. 设置认证提供程序

接下来,获取你的认证服务器的 URL 和用于认证的私钥。 由于你使用的是 Supabase,可以在 Supabase 控制台中完成此操作:

  1. 在左侧边栏中,点击 t️⚙ Project Settings",然后点击 "API"
  2. 复制你的项目 URL 并将其添加到你的 .env 文件中

    echo "SUPABASE_URL=your-project-url" >> .env
    
    1. 复制你的服务角色密钥并将其添加到你的 .env 文件中:

    echo "SUPABASE_SERVICE_KEY=your-service-role-key" >> .env
    
    1. 复制你的 "anon public" 密钥并记录下来。这将在你设置客户端代码时用到。

    SUPABASE_URL=your-project-url
    SUPABASE_SERVICE_KEY=your-service-role-key
    

3. 实现令牌验证

在之前的教程中,你使用了 Auth 对象来 验证硬编码的令牌添加资源所有权

现在你将升级认证功能,以验证来自 Supabase 的真实 JWT 令牌。主要的更改将集中在 @auth.authenticate 装饰函数中:

  • 不再检查硬编码的令牌列表,而是通过 HTTP 请求到 Supabase 验证令牌。
  • 你将从验证后的令牌中提取真实用户信息(ID、邮箱)。
  • 现有的资源授权逻辑保持不变。

更新 src/security/auth.py 来实现这一功能:

src/security/auth.py
import os
import httpx
from langgraph_sdk import Auth

auth = Auth()

# 这是从你上面创建的 `.env` 文件中加载的
SUPABASE_URL = os.environ["SUPABASE_URL"]
SUPABASE_SERVICE_KEY = os.environ["SUPABASE_SERVICE_KEY"]


@auth.authenticate
async def get_current_user(authorization: str | None):
    """验证 JWT 令牌并提取用户信息。"""
    assert authorization
    scheme, token = authorization.split()
    assert scheme.lower() == "bearer"

    try:
        # 使用认证提供者验证令牌
        async with httpx.AsyncClient() as client:
            response = await client.get(
                f"{SUPABASE_URL}/auth/v1/user",
                headers={
                    "Authorization": authorization,
                    "apiKey": SUPABASE_SERVICE_KEY,
                },
            )
            assert response.status_code == 200
            user = response.json()
            return {
                "identity": user["id"],  # 唯一用户标识符
                "email": user["email"],
                "is_authenticated": True,
            }
    except Exception as e:
        raise Auth.exceptions.HTTPException(status_code=401, detail=str(e))

# ...其余部分与之前相同

# 保留我们上一个教程中的资源授权
@auth.on
async def add_owner(ctx, value):
    """使用资源元数据使资源仅对创建者私有。"""
    filters = {"owner": ctx.user.identity}
    metadata = value.setdefault("metadata", {})
    metadata.update(filters)
    return filters

最重要的变化是我们现在使用真实的认证服务器来验证令牌。我们的认证处理程序拥有我们 Supabase 项目的私钥,可以用来验证用户的令牌并提取他们的信息。

4. 测试认证流程

让我们测试新的认证流程。你可以在一个文件或笔记本中运行以下代码。你需要提供:

  • 一个有效的电子邮件地址
  • 一个 Supabase 项目 URL(来自 上方
  • 一个 Supabase 匿名 公钥(同样来自 上方
import os
import httpx
from getpass import getpass
from langgraph_sdk import get_client


# 从命令行获取电子邮件
email = getpass("Enter your email: ")
base_email = email.split("@")
password = "secure-password"  # CHANGEME
email1 = f"{base_email[0]}+1@{base_email[1]}"
email2 = f"{base_email[0]}+2@{base_email[1]}"

SUPABASE_URL = os.environ.get("SUPABASE_URL")
if not SUPABASE_URL:
    SUPABASE_URL = getpass("Enter your Supabase project URL: ")

# 这是你的 PUBLIC 匿名密钥(在客户端使用是安全的)
# 不要将它与用于服务角色的秘密密钥混淆
SUPABASE_ANON_KEY = os.environ.get("SUPABASE_ANON_KEY")
if not SUPABASE_ANON_KEY:
    SUPABASE_ANON_KEY = getpass("Enter your public Supabase anon key: ")


async def sign_up(email: str, password: str):
    """创建新用户账户."""
    async with httpx.AsyncClient() as client:
        response = await client.post(
            f"{SUPABASE_URL}/auth/v1/signup",
            json={"email": email, "password": password},
            headers={"apiKey": SUPABASE_ANON_KEY},
        )
        assert response.status_code == 200
        return response.json()

# 创建两个测试用户
print(f"Creating test users: {email1} and {email2}")
await sign_up(email1, password)
await sign_up(email2, password)

⚠️ 在继续之前:检查你的电子邮件并点击两个确认链接。Supabase 会在用户确认电子邮件之前拒绝 /login 请求。

现在测试用户只能看到自己的数据。确保服务器正在运行(运行 langgraph dev)后再继续。以下片段需要你在之前设置认证提供者时从 Supabase 面板复制的 "anon 公共" 密钥。

async def login(email: str, password: str):
    """为现有用户获取访问令牌."""
    async with httpx.AsyncClient() as client:
        response = await client.post(
            f"{SUPABASE_URL}/auth/v1/token?grant_type=password",
            json={
                "email": email,
                "password": password
            },
            headers={
                "apikey": SUPABASE_ANON_KEY,
                "Content-Type": "application/json"
            },
        )
        assert response.status_code == 200
        return response.json()["access_token"]


# 以用户 1 身份登录
user1_token = await login(email1, password)
user1_client = get_client(
    url="http://localhost:2024", headers={"Authorization": f"Bearer {user1_token}"}
)

# 以用户 1 身份创建线程
thread = await user1_client.threads.create()
print(f"✅ User 1 created thread: {thread['thread_id']}")

# 尝试不带令牌访问
unauthenticated_client = get_client(url="http://localhost:2024")
try:
    await unauthenticated_client.threads.create()
    print("❌ Unauthenticated access should fail!")
except Exception as e:
    print("✅ Unauthenticated access blocked:", e)

# 以用户 2 身份尝试访问用户 1 的线程
user2_token = await login(email2, password)
user2_client = get_client(
    url="http://localhost:2024", headers={"Authorization": f"Bearer {user2_token}"}
)

try:
    await user2_client.threads.get(thread["thread_id"])
    print("❌ User 2 shouldn't see User 1's thread!")
except Exception as e:
    print("✅ User 2 blocked from User 1's thread:", e)
输出应该如下所示:

 User 1 created thread: d6af3754-95df-4176-aa10-dbd8dca40f1a
 Unauthenticated access blocked: Client error '403 Forbidden' for url 'http://localhost:2024/threads'
 User 2 blocked from User 1's thread: Client error '404 Not Found' for url 'http://localhost:2024/threads/d6af3754-95df-4176-aa10-dbd8dca40f1a'

你的认证和授权机制正在协同工作:

  1. 用户必须登录才能访问机器人
  2. 每个用户只能看到自己的线程

所有用户都由 Supabase 认证提供程序管理,因此你不需要实现任何额外的用户管理逻辑。

下一步

你已成功为你的 LangGraph 应用程序构建了一个生产就绪的认证系统!让我们回顾一下你所完成的内容:

  1. 设置了一个认证提供者(在此示例中使用的是 Supabase)
  2. 添加了带有电子邮件/密码认证的真实用户账户
  3. 将 JWT 令牌验证集成到你的 LangGraph 服务器中
  4. 实现了适当的授权机制,确保用户只能访问自己的数据
  5. 创建了一个基础架构,准备好应对你的下一个认证挑战 🚀

现在你已经有了生产环境的认证系统,可以考虑以下事项:

  1. 使用你偏好的框架构建一个网页界面(查看 Custom Auth 模板以获取示例)
  2. 了解更多关于认证和授权其他方面的知识,请参阅 认证概念指南
  3. 阅读 参考文档 后自定义你的处理器和进一步设置。