> Discover all available pages from the documentation index: https://mastra.zisheng.pro/llms.txt # Supabase `@mastra/auth-supabase` 包使用 Supabase Auth 为 Mastra 提供身份验证。它使用 Supabase 的身份验证系统验证传入请求,并通过 `auth` 选项与 Mastra 服务器集成。 ## 前置条件 本示例使用 Supabase Auth。请务必将 Supabase 凭据添加到 `.env` 文件,并确保 Supabase 项目已正确配置。 ```env SUPABASE_URL=https://your-project.supabase.co SUPABASE_ANON_KEY=your-anon-key ``` > **备注:** 请检查 Supabase Row Level Security (RLS) 设置,以确保数据访问控制正确。 ## 安装 在使用 `MastraAuthSupabase` 类之前,必须安装 `@mastra/auth-supabase` 包。 **npm**: ```bash npm install @mastra/auth-supabase@latest ``` **pnpm**: ```bash pnpm add @mastra/auth-supabase@latest ``` **Yarn**: ```bash yarn add @mastra/auth-supabase@latest ``` **Bun**: ```bash bun add @mastra/auth-supabase@latest ``` ## 用法示例 ```typescript import { Mastra } from '@mastra/core' import { MastraAuthSupabase } from '@mastra/auth-supabase' export const mastra = new Mastra({ server: { auth: new MastraAuthSupabase({ url: process.env.SUPABASE_URL, anonKey: process.env.SUPABASE_ANON_KEY, }), }, }) ``` > **信息:** 默认 `authorizeUser` 方法会检查 `public` schema 中 `users` 表的 `isAdmin` 列。要自定义用户授权,请在构造 Provider 时提供自定义 `authorizeUser` 函数。 > > 有关所有可用的配置选项,请参阅 [MastraAuthSupabase](https://mastra.zisheng.pro/reference/auth/supabase)。 ## 客户端设置 使用 Supabase 身份验证时,需要在客户端从 Supabase 获取访问令牌,并将其传递给 Mastra 请求。 ### 获取访问令牌 使用 Supabase 客户端对用户进行身份验证并获取其访问令牌: ```typescript import { createClient } from '@supabase/supabase-js' const supabase = createClient('', '') const authTokenResponse = await supabase.auth.signInWithPassword({ email: "", password: "", }) const accessToken = authTokenResponse.data?.session?.access_token ``` > **备注:** 有关 OAuth、magic link 等其他身份验证方法,请参阅 [Supabase 文档](https://supabase.com/docs/guides/auth)。 ## 配置 `MastraClient` 启用 `auth` 后,使用 `MastraClient` 发出的所有请求都必须在 `Authorization` 标头中包含有效的 Supabase 访问令牌: ```typescript import { MastraClient } from '@mastra/client-js' export const mastraClient = new MastraClient({ baseUrl: 'https://', headers: { Authorization: `Bearer ${accessToken}`, }, }) ``` > **信息:** 访问令牌在 Authorization 标头中必须带有 `Bearer` 前缀。 > > 有关更多配置选项,请参阅 [Mastra Client SDK](https://mastra.zisheng.pro/docs/server/mastra-client)。 ### 发出经过身份验证的请求 使用 Supabase 访问令牌配置 `MastraClient` 后,即可发送经过身份验证的请求: **React**: ```tsx import { mastraClient } from '../../lib/mastra-client' export const TestAgent = () => { async function handleClick() { const agent = mastraClient.getAgent('weatherAgent') const response = await agent.generate("What's the weather like in New York") console.log(response) } return } ``` **cURL**: ```bash curl -X POST http://localhost:4111/api/agents/weatherAgent/generate \ -H "Content-Type: application/json" \ -H "Authorization: Bearer " \ -d '{ "messages": "Weather in London" }' ```