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 安装指南挂载 /api/auth/* 路由(或配置的基础路径)。
安装安装的直接链接
安装 @mastra/auth-better-auth 包:
- npm
- pnpm
- Yarn
- Bun
npm install @mastra/auth-better-auth
pnpm add @mastra/auth-better-auth
yarn add @mastra/auth-better-auth
bun add @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/*'],
})
匹配规则匹配规则的直接链接
public和protected接受精确路径、通配符模式(例如/api/*)和路径参数(例如/users/:id)。- 对于特定方法的规则,请使用
["/api/agents", ["GET", "POST"]]这样的元组。 - 如果路由同时匹配
public和protected,则以public为准,不需要身份验证。 - 如果两者均不匹配,默认将路由视为受保护路由(除非路由明确标记为
requiresAuth: false)。
客户端设置客户端设置的直接链接
启用身份验证后,对 Mastra 内置路由的请求需要身份验证。也就是说,客户端需要发送 Better Auth 设置用于认证请求的凭据。
Cookie 会话(推荐)Cookie 会话(推荐)的直接链接
如果 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。
发出经过身份验证的请求发出经过身份验证的请求的直接链接
- React
- cURL
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>
}
curl -X POST http://localhost:4111/api/agents/weatherAgent/generate \
-H "Content-Type: application/json" \
-H "Authorization: Bearer <your-token>" \
-d '{
"messages": "Weather in London"
}'
故障排除故障排除的直接链接
- 每个请求都返回 401:确认已挂载 Better Auth handler,且应用可以创建有效会话。检查客户端是否发送了会话 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 配置。