Skip to main content

SimpleAuth 类

🌐 SimpleAuth Class

SimpleAuth 类提供基于令牌的身份验证,通过简单的令牌与用户映射实现。它包含在 @mastra/core/server 中,适用于开发、测试以及简单的 API 密钥认证场景。

🌐 The SimpleAuth class provides token-based authentication using a simple token-to-user mapping. It's included in @mastra/core/server and is useful for development, testing, and simple API key authentication scenarios.

用例
Direct link to 用例

🌐 Use Cases

  • 本地开发与测试
  • 简单的 API 密钥认证
  • 在集成完整身份提供商之前进行原型设计
  • 使用静态令牌的内部服务

安装
Direct link to 安装

🌐 Installation

SimpleAuth 已包含在 @mastra/core 中,无需额外安装任何包。

🌐 SimpleAuth is included in @mastra/core, no additional packages required.

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

使用示例
Direct link to 使用示例

🌐 Usage Example

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',
},
},
}),
},
});

配置选项
Direct link to 配置选项

🌐 Configuration Options

选项类型必填描述
tokensRecord<string, TUser>令牌到用户对象的映射
headersstring | string[]需检查令牌的附加头信息
namestring用于日志记录的提供商名称
authorizeUser(user, request) => boolean自定义授权函数
protected(RegExp | string)[]需要认证的路径
public(RegExp | string)[]跳过认证的路径

默认头
Direct link to 默认头

🌐 Default Headers

SimpleAuth 默认会检查这些头信息:

🌐 SimpleAuth checks these headers by default:

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

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

🌐 Add custom headers using the headers option:

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

进行认证请求
Direct link to 进行认证请求

🌐 Making Authenticated Requests

Authorization 头中包含你的令牌:

🌐 Include your token in the Authorization header:

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 前缀:

🌐 Or without the Bearer prefix:

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

自定义授权
Direct link to 自定义授权

🌐 Custom Authorization

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

🌐 Add role-based or custom authorization logic:

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;
},
});

环境变量
Direct link to 环境变量

🌐 Environment Variables

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

🌐 For production-like setups, load tokens from environment variables:

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
Direct link to 使用 MastraClient

🌐 With MastraClient

使用你的令牌配置客户端:

🌐 Configure the client with your token:

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');

限制
Direct link to 限制

🌐 Limitations

SimpleAuth 设计注重简洁,而非生产环境安全:

🌐 SimpleAuth is designed for simplicity, not production security:

  • 令牌存储在内存中
  • 没有令牌过期或刷新
  • 没有加密验证
  • 所有令牌必须在启动时已知

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

🌐 For production applications, consider using JWT, Clerk, Auth0, or another identity provider.

🌐 Related