> Discover all available pages from the documentation index: https://mastra.zisheng.pro/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 handler(以便应用登录用户或创建会话),请按照 [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/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 令牌 可以将签名的会话令牌作为 Bearer 令牌传递。从 Better Auth 客户端会话中获取该令牌,并将其包含在 `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/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 handler,且应用可以创建有效会话。检查客户端是否发送了会话 Cookie 或 `Authorization: Bearer ` 标头。 - **未跨域发送 Cookie**:在 `MastraClient` 中设置 `credentials: "include"`,并使用前端来源和 `credentials: true` 配置 `server.cors`。 - **Bearer 令牌被拒绝**:确保传递完整的已签名会话令牌(来自 `authClient.getSession()`),而非原始或未签名令牌。 - **基础 URL 问题**:在 `betterAuth({ ... })` 中设置 `baseURL`,或设置 `BETTER_AUTH_URL`。 - **数据库连接错误**:验证 `DATABASE_URL` 和数据库 Provider 配置。