Supabase
@mastra/auth-supabase 套件使用 Supabase Auth 為 Mastra 提供身份驗證。它會透過 Supabase 的身份驗證系統驗證傳入的請求,並使用 auth 選項與 Mastra 伺服器整合。
先決條件先決條件 的直接連結
此範例使用 Supabase Auth。請確保已將 Supabase 憑證加入 .env 文件,並已正確設定 Supabase 項目。
SUPABASE_URL=https://your-project.supabase.co
SUPABASE_ANON_KEY=your-anon-key
請檢查 Supabase Row Level Security (RLS) 設定,確保資料存取控制正確。
安裝安裝 的直接連結
使用 MastraAuthSupabase 類別前,必須先安裝 @mastra/auth-supabase 套件。
- npm
- pnpm
- Yarn
- Bun
npm install @mastra/auth-supabase@latest
pnpm add @mastra/auth-supabase@latest
yarn add @mastra/auth-supabase@latest
bun add @mastra/auth-supabase@latest
使用範例使用範例 的直接連結
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 查看所有可用的設定選項。
用戶端設定用戶端設定 的直接連結
使用 Supabase auth 時,你需要在用戶端從 Supabase 取得存取權杖,並將其傳送至 Mastra 請求。
取得存取權杖取得存取權杖 的直接連結
使用 Supabase 用戶端驗證用戶並取得其存取權杖:
import { createClient } from '@supabase/supabase-js'
const supabase = createClient('<supabase-url>', '<supabase-key>')
const authTokenResponse = await supabase.auth.signInWithPassword({
email: "<user's email>",
password: "<user's password>",
})
const accessToken = authTokenResponse.data?.session?.access_token
如需了解 OAuth、magic links 等其他身份驗證方法,請參閱 Supabase 文檔。
設定 MastraClientconfiguring-mastraclient 的直接連結
啟用 auth 後,所有透過 MastraClient 發出的請求都必須在 Authorization 標頭中包含有效的 Supabase 存取權杖:
import { MastraClient } from '@mastra/client-js'
export const mastraClient = new MastraClient({
baseUrl: 'https://<mastra-api-url>',
headers: {
Authorization: `Bearer ${accessToken}`,
},
})
在 Authorization 標頭中,存取權杖必須以 Bearer 作為前綴。
請前往 Mastra Client SDK 查看更多設定選項。
發出已驗證的請求發出已驗證的請求 的直接連結
使用 Supabase 存取權杖設定 MastraClient 後,便可發出已驗證的請求:
- React
- cURL
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 <button onClick={handleClick}>Test Agent</button>
}
curl -X POST http://localhost:4111/api/agents/weatherAgent/generate \
-H "Content-Type: application/json" \
-H "Authorization: Bearer <your-supabase-access-token>" \
-d '{
"messages": "Weather in London"
}'