跳至主要內容

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。