跳到主要内容

Simple Auth

SimpleAuth 类通过基础的令牌到用户映射提供基于令牌的身份验证。它包含在 @mastra/core/server 中,适用于开发、测试和基础 API 密钥身份验证场景。

使用场景
使用场景的直接链接

  • 本地开发和测试
  • 简单的 API 密钥身份验证
  • 集成完整身份 Provider 之前的原型设计
  • 使用静态令牌的内部服务

安装
安装的直接链接

SimpleAuth 包含在 @mastra/core 中,无需安装其他包。

import { SimpleAuth } from '@mastra/core/server'

用法示例
用法示例的直接链接

src/mastra/index.ts
import { Mastra } from '@mastra/core'
import { SimpleAuth } from '@mastra/core/server'

// Define your user type
type User = {
id: string
name: string
role: 'admin' | 'user'
}

export const mastra = new Mastra({
server: {
auth: new SimpleAuth<User>({
tokens: {
'sk-admin-token-123': {
id: 'user-1',
name: 'Admin User',
role: 'admin',
},
'sk-user-token-456': {
id: 'user-2',
name: 'Regular User',
role: 'user',
},
},
}),
},
})

配置选项
配置选项的直接链接

选项类型必填描述
tokensRecord<string, TUser>令牌到用户对象的映射
headersstring | string[]要检查令牌的其他标头
namestring用于日志记录的 Provider 名称
authorizeUser(user, request) => boolean自定义授权函数
protected(RegExp | string)[]需要身份验证的路径
public(RegExp | string)[]绕过身份验证的路径

默认标头
默认标头的直接链接

SimpleAuth 默认检查以下标头:

  • Authorization(带或不带 Bearer 前缀)
  • X-Playground-Access

使用 headers 选项添加自定义标头:

new SimpleAuth({
tokens: {/* ... */},
headers: ['X-API-Key', 'X-Custom-Auth'],
})

发出经过身份验证的请求
发出经过身份验证的请求的直接链接

Authorization 标头中包含令牌:

curl -X POST http://localhost:4111/api/agents/myAgent/generate \
-H "Content-Type: application/json" \
-H "Authorization: Bearer sk-admin-token-123" \
-d '{"messages": "Hello"}'

也可以不使用 Bearer 前缀:

curl -X POST http://localhost:4111/api/agents/myAgent/generate \
-H "Content-Type: application/json" \
-H "Authorization: sk-admin-token-123" \
-d '{"messages": "Hello"}'

自定义授权
自定义授权的直接链接

添加基于角色或自定义的授权逻辑:

new SimpleAuth<User>({
tokens: {
'sk-admin-token': { id: '1', name: 'Admin', role: 'admin' },
'sk-user-token': { id: '2', name: 'User', role: 'user' },
},
authorizeUser: (user, request) => {
// Only admins can access /admin routes
if (request.url.includes('/admin')) {
return user.role === 'admin'
}
return true
},
})

环境变量
环境变量的直接链接

对于类似生产环境的设置,请从环境变量加载令牌:

const tokens: Record<string, User> = {}

// Load from environment
const adminToken = process.env.ADMIN_API_KEY
if (adminToken) {
tokens[adminToken] = { id: 'admin', name: 'Admin', role: 'admin' }
}

const userToken = process.env.USER_API_KEY
if (userToken) {
tokens[userToken] = { id: 'user', name: 'User', role: 'user' }
}

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

MastraClient 配合使用
with-mastraclient的直接链接

使用令牌配置客户端:

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

const client = new MastraClient({
baseUrl: 'http://localhost:4111',
headers: {
Authorization: 'Bearer sk-admin-token-123',
},
})

const agent = client.getAgent('myAgent')
const response = await agent.generate('Hello')

限制
限制的直接链接

SimpleAuth 以简单易用为设计目标,并非为生产环境安全而设计:

  • 令牌存储在内存中
  • 不支持令牌过期或刷新
  • 不进行加密验证
  • 所有令牌都必须在启动时已知

对于生产应用,请考虑使用 JWTClerkAuth0 或其他身份 Provider。