> Discover all available pages from the documentation index: https://mastra.zisheng.pro/zh-HK/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` 方法會檢查 `isAdmin` 欄,該欄位於 `users` 表格,而表格位於 `public` schema。要自訂用戶授權,請在建立 Provider 時提供自訂的 `authorizeUser` 函數。 > > 請前往 [MastraAuthSupabase](https://mastra.zisheng.pro/zh-HK/reference/auth/supabase) 查看所有可用的設定選項。 ## 用戶端設定 使用 Supabase auth 時,你需要在用戶端從 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 links 等其他身份驗證方法,請參閱 [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/zh-HK/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" }' ```