跳至主要內容

Better Auth

@mastra/auth-better-auth 套件透過 Better Auth 為 Mastra 提供驗證功能。它會使用你的 Better Auth 執行個體驗證傳入的請求,並透過 server.auth 選項與 Mastra 伺服器整合。

先決條件
「先決條件」的直接連結

此範例使用 Better Auth。請確認已設定 Better Auth 執行個體與環境變數。

.env
# Required by Better Auth
BETTER_AUTH_SECRET=... # at least 32 chars
BETTER_AUTH_URL=http://localhost:3000

# Example DB URL used by the snippet below (adjust for your setup)
DATABASE_URL=postgres://...
備註

為了安全性與穩定性,Better Auth 建議明確設定 baseURL(或透過 BETTER_AUTH_URL 設定)。

如果尚未掛載 Better Auth 的處理常式(讓應用程式可以登入使用者及建立工作階段),請依照 Better Auth 安裝指南掛載 /api/auth/* 路由(或你設定的基礎路徑)。

安裝
「安裝」的直接連結

安裝 @mastra/auth-better-auth 套件:

npm install @mastra/auth-better-auth

使用範例
「使用範例」的直接連結

首先,建立 Better Auth 執行個體:

lib/auth.ts
import { betterAuth } from 'better-auth'

export const auth = betterAuth({
database: {
provider: 'postgresql',
url: process.env.DATABASE_URL!,
},
emailAndPassword: {
enabled: true,
},
baseURL: process.env.BETTER_AUTH_URL,
secret: process.env.BETTER_AUTH_SECRET,
})

接著,將它與 Mastra 搭配使用:

src/mastra/index.ts
import { Mastra } from '@mastra/core'
import { MastraAuthBetterAuth } from '@mastra/auth-better-auth'
import { auth } from '@/lib/auth'

const mastraAuth = new MastraAuthBetterAuth({
auth,
})

export const mastra = new Mastra({
server: {
auth: mastraAuth,
},
})

請參閱 MastraAuthBetterAuth,瞭解所有可用的設定選項。

自訂授權
「自訂授權」的直接連結

const mastraAuth = new MastraAuthBetterAuth({
auth,
async authorizeUser(user) {
// Example: only allow verified emails
return user?.user?.emailVerified === true
},
})

路由設定
「路由設定」的直接連結

const mastraAuth = new MastraAuthBetterAuth({
auth,
public: ['/health', '/api/status'],
protected: ['/api/*', '/admin/*'],
})

比對規則
「比對規則」的直接連結

  • publicprotected 接受完整路徑、萬用字元模式(例如 /api/*)及路徑參數(例如 /users/:id)。
  • 若要設定特定 HTTP 方法的規則,請使用 ["/api/agents", ["GET", "POST"]] 這類元組。
  • 如果路由同時符合 publicprotected,則以 public 為優先,不需要驗證。
  • 如果兩者都不符合,預設會將路由視為受保護(除非路由明確標記為 requiresAuth: false)。

用戶端設定
「用戶端設定」的直接連結

啟用驗證後,向 Mastra 內建路由發出的請求必須通過驗證。實際上,這表示用戶端必須傳送 Better Auth 設定用來驗證請求的憑證。

如果 Better Auth 設定使用 Cookie,請將用戶端設定為傳送憑證。若為跨來源請求(例如在 :3000 執行的 Next.js 呼叫位於 :4111 的 Mastra),請在 Mastra 伺服器上啟用 CORS 憑證:

src/mastra/index.ts
export const mastra = new Mastra({
server: {
auth: mastraAuth,
cors: {
origin: 'http://localhost:3000', // your frontend origin
credentials: true,
},
},
})

接著,設定用戶端以包含憑證:

import { MastraClient } from '@mastra/client-js'

export const mastraClient = new MastraClient({
baseUrl: 'http://localhost:4111',
credentials: 'include',
})

如果直接呼叫 API,也請在 fetch 中包含憑證:

await fetch('http://localhost:4111/api/agents/weatherAgent/generate', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
credentials: 'include',
body: JSON.stringify({ messages: 'Weather in London' }),
})

Bearer 權杖
「Bearer 權杖」的直接連結

你可以將已簽署的工作階段權杖當作 Bearer 權杖傳送。請從 Better Auth 用戶端工作階段取得權杖,並將其加入 Authorization 標頭:

import { MastraClient } from '@mastra/client-js'
import { authClient } from './auth-client' // your Better Auth client

const session = await authClient.getSession()

export const mastraClient = new MastraClient({
baseUrl: 'http://localhost:4111',
headers: {
Authorization: `Bearer ${session.data?.session.token}`,
},
})

請參閱 Mastra Client SDK,瞭解更多設定選項。

發出已驗證的請求
「發出已驗證的請求」的直接連結

src/components/test-agent.tsx
import { mastraClient } from '../lib/mastra-client'

export const TestAgent = () => {
async function handleClick() {
const agent = mastraClient.getAgent('weatherAgent')

const response = await agent.generate('Weather in London')

console.log(response)
}

return <button onClick={handleClick}>Test Agent</button>
}

疑難排解
「疑難排解」的直接連結

  • 每個請求都傳回 401:確認已掛載 Better Auth 處理常式,且應用程式可以建立有效的工作階段。請檢查用戶端是否傳送工作階段 Cookie 或 Authorization: Bearer <signed-token> 標頭。
  • 跨來源時未傳送 Cookie:在 MastraClient 中設定 credentials: "include",並以你的前端來源及 credentials: true 設定 server.cors
  • Bearer 權杖遭拒:請確認傳入完整的已簽署工作階段權杖(來自 authClient.getSession()),而非原始或未簽署的權杖。
  • 基礎 URL 問題:在 betterAuth({ ... }) 中設定 baseURL,或設定 BETTER_AUTH_URL
  • 資料庫連線錯誤:確認 DATABASE_URL 及資料庫 Provider 設定。