> Discover all available pages from the documentation index: https://mastra.zisheng.pro/zh-HK/llms.txt
# 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 安裝指南](https://www.better-auth.com/docs/installation)掛載 `/api/auth/*` 路由(或你所設定的基礎路徑)。
## 安裝
安裝 `@mastra/auth-better-auth` 套件:
**npm**:
```bash
npm install @mastra/auth-better-auth
```
**pnpm**:
```bash
pnpm add @mastra/auth-better-auth
```
**Yarn**:
```bash
yarn add @mastra/auth-better-auth
```
**Bun**:
```bash
bun add @mastra/auth-better-auth
```
## 使用範例
首先,建立你的 Better 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 配合使用:
```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](https://mastra.zisheng.pro/zh-HK/reference/auth/better-auth),了解所有可用的設定選項。
## 自訂授權
```ts
const mastraAuth = new MastraAuthBetterAuth({
auth,
async authorizeUser(user) {
// Example: only allow verified emails
return user?.user?.emailVerified === true
},
})
```
## 路由設定
```ts
const mastraAuth = new MastraAuthBetterAuth({
auth,
public: ['/health', '/api/status'],
protected: ['/api/*', '/admin/*'],
})
```
### 配對規則
- `public` 和 `protected` 接受完全相符的路徑、萬用字元模式(例如 `/api/*`),以及路徑參數(例如 `/users/:id`)。
- 如要設定特定方法的規則,請使用 `["/api/agents", ["GET", "POST"]]` 之類的元組。
- 如果路由同時符合 `public` 和 `protected`,會以 `public` 為準,毋須身份驗證。
- 如果兩者均不符合,路由預設會視為受保護(除非路由明確標記為 `requiresAuth: false`)。
## 用戶端設定
啟用身份驗證後,向 Mastra 內置路由發出的請求必須通過身份驗證。實際上,這表示你的用戶端需要傳送 Better Auth 設定用於已驗證請求的憑證。
### Cookie 工作階段(建議)
如果你的 Better Auth 設定使用 Cookie,請將用戶端設為傳送憑證。對於跨來源請求(例如在 `:3000` 上執行的 Next.js 呼叫 `:4111` 上的 Mastra),請在 Mastra 伺服器上啟用 CORS 憑證:
```ts
export const mastra = new Mastra({
server: {
auth: mastraAuth,
cors: {
origin: 'http://localhost:3000', // your frontend origin
credentials: true,
},
},
})
```
然後,將用戶端設為包含憑證:
```ts
import { MastraClient } from '@mastra/client-js'
export const mastraClient = new MastraClient({
baseUrl: 'http://localhost:4111',
credentials: 'include',
})
```
如果你直接呼叫 API,也請在 `fetch` 中包含憑證:
```ts
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 token
你可以將已簽署的工作階段 token 作為 Bearer token 傳送。從 Better Auth 用戶端工作階段取得該 token,並將它加入 `Authorization` 標頭:
```ts
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](https://mastra.zisheng.pro/zh-HK/docs/server/mastra-client),了解更多設定選項。
### 發出已驗證的請求
**React**:
```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
}
```
**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"
}'
```
## 疑難排解
- **每個請求都傳回 401**:確認已掛載 Better Auth 處理常式,而且你的應用程式能夠建立有效的工作階段。檢查用戶端是否有傳送工作階段 Cookie 或 `Authorization: Bearer ` 標頭。
- **跨來源時未有傳送 Cookie**:設定 `credentials: "include"` 至 `MastraClient`,並設定 `server.cors`,使用你的前端來源及 `credentials: true`。
- **Bearer token 被拒絕**:確保傳送的是完整、已簽署的工作階段 token(來自 `authClient.getSession()`),而非原始或未簽署的 token。
- **基礎 URL 問題**:設定 `baseURL` 至 `betterAuth({ ... })`,或設定 `BETTER_AUTH_URL`。
- **資料庫連線錯誤**:驗證 `DATABASE_URL` 及資料庫 Provider 設定。