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',
},
},
}),
},
})
設定選項「設定選項」的直接連結
| 選項 | 類型 | 必要 | 說明 |
|---|---|---|---|
tokens | Record<string, TUser> | 是 | 權杖對使用者物件的對應 |
headers | string | string[] | 否 | 要檢查權杖的其他標頭 |
name | string | 否 | 用於記錄的 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 的設計重點是簡易性,而非正式環境的安全性:
- 權杖儲存在記憶體中
- 不支援權杖到期或重新整理
- 不執行密碼編譯驗證
- 啟動時必須已知所有權杖