跳至主要內容

自訂驗證 Provider

自訂驗證 Provider 可讓你為內置 Provider 未涵蓋的身份系統實作驗證。擴充 MastraAuthProvider 基礎類別,即可與任何驗證系統整合。

概覽
概覽 的直接連結

驗證 Provider 負責處理傳入請求的驗證和授權:

  • 驗證 token 並擷取用戶
  • 用戶授權邏輯
  • 按路徑控制存取權限(公開/受保護路由)

建立自訂驗證 Provider 以支援:

  • 自行託管的身份系統
  • 自訂 token 格式或驗證邏輯
  • 專門的授權規則
  • 企業 SSO 整合

建立自訂驗證 Provider
建立自訂驗證 Provider 的直接連結

擴充 MastraAuthProvider 類別並實作必要方法:

import { MastraAuthProvider } from '@mastra/core/server'
import type { MastraAuthProviderOptions } from '@mastra/core/server'
import type { HonoRequest } from 'hono'

// Define your user type
type MyUser = {
id: string
email: string
roles: string[]
}

// Define options for your provider
interface MyAuthOptions extends MastraAuthProviderOptions<MyUser> {
apiUrl?: string
apiKey?: string
}

export class MyAuthProvider extends MastraAuthProvider<MyUser> {
protected apiUrl: string
protected apiKey: string

constructor(options?: MyAuthOptions) {
// Call super with a name for logging/debugging
super({ name: options?.name ?? 'my-auth' })

const apiUrl = options?.apiUrl ?? process.env.MY_AUTH_API_URL
const apiKey = options?.apiKey ?? process.env.MY_AUTH_API_KEY

if (!apiUrl || !apiKey) {
throw new Error(
'Auth API URL and API key are required. Provide them in options or set MY_AUTH_API_URL and MY_AUTH_API_KEY environment variables.',
)
}

this.apiUrl = apiUrl
this.apiKey = apiKey

// Register any custom options (authorizeUser override, public/protected paths)
this.registerOptions(options)
}

/**
* Verify the token and return the user
* Return null if authentication fails
*/
async authenticateToken(token: string, request: HonoRequest): Promise<MyUser | null> {
try {
const response = await fetch(`${this.apiUrl}/verify`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-API-Key': this.apiKey,
},
body: JSON.stringify({ token }),
})

if (!response.ok) {
return null
}

const user = await response.json()
return user
} catch (error) {
console.error('Token verification failed:', error)
return null
}
}

/**
* Check if the authenticated user is authorized
* Return true to allow access, false to deny
*/
async authorizeUser(user: MyUser, request: HonoRequest): Promise<boolean> {
// Basic authorization: user must exist and have an ID
return !!user?.id
}
}

必要方法
必要方法 的直接連結

authenticateToken()
authenticatetoken 的直接連結

驗證傳入的 token;如有效則傳回用戶物件,如驗證失敗則傳回 null

async authenticateToken(token: string, request: HonoRequest): Promise<TUser | null>
參數類型說明
tokenstringAuthorization header 擷取的 bearer token
requestHonoRequest傳入的請求物件(存取 header、cookie 等)

傳回值:驗證成功時傳回用戶物件,失敗時傳回 null

系統會自動從 Authorization: Bearer <token> header 擷取 token。如需存取其他 header 或 cookie,請使用 request 參數。

authorizeUser()
authorizeuser 的直接連結

判斷已驗證用戶是否獲准存取資源。

async authorizeUser(user: TUser, request: HonoRequest): Promise<boolean> | boolean
參數類型說明
userTUserauthenticateToken 傳回的用戶物件
requestHonoRequest傳入的請求物件

傳回值:傳回 true 以允許存取,傳回 false 則拒絕存取(傳回 403 Forbidden)。

配置選項
配置選項 的直接連結

MastraAuthProviderOptions interface 支援以下選項:

選項類型說明
namestring用於記錄/除錯的 Provider 名稱
authorizeUser(user, request) => Promise<boolean> | boolean自訂授權函數
protected(RegExp | string | [string, Methods | Methods[]])[]需要驗證的路徑
public(RegExp | string | [string, Methods | Methods[]])[]略過驗證的路徑

路徑模式
路徑模式 的直接連結

使用模式配對配置哪些路徑需要驗證:

const auth = new MyAuthProvider({
// Paths that require authentication
protected: [
'/api/*', // Wildcard: all /api routes
'/admin/*', // Wildcard: all /admin routes
/^\/secure\/.*/, // Regex pattern
],

// Paths that bypass authentication
public: [
'/health', // Exact match
'/api/status', // Exact match
['/api/webhook', 'POST'], // Only POST requests to /api/webhook
],
})

使用你的驗證 Provider
使用你的驗證 Provider 的直接連結

在 Mastra instance 註冊你的自訂驗證 Provider:

import { Mastra } from '@mastra/core'
import { MyAuthProvider } from './my-auth-provider'

export const mastra = new Mastra({
server: {
auth: new MyAuthProvider({
apiUrl: process.env.MY_AUTH_API_URL,
apiKey: process.env.MY_AUTH_API_KEY,
}),
},
})

輔助工具
輔助工具 的直接連結

@mastra/auth 依賴套件提供處理常見 token 驗證模式的工具:

JWT 驗證
JWT 驗證 的直接連結

import { verifyHmac, verifyJwks, decodeToken, getTokenIssuer } from '@mastra/auth'

// Verify HMAC-signed JWT
const payload = await verifyHmac(token, 'your-secret-key')

// Verify with JWKS (for OAuth providers)
const payload = await verifyJwks(token, 'https://provider.com/.well-known/jwks.json')

// Decode without verification (for inspection)
const decoded = await decodeToken(token)

// Get the issuer from a decoded token
const issuer = getTokenIssuer(decoded)

範例:以 JWKS 為基礎的 Provider
範例:以 JWKS 為基礎的 Provider 的直接連結

import { MastraAuthProvider } from '@mastra/core/server'
import type { MastraAuthProviderOptions } from '@mastra/core/server'
import { verifyJwks } from '@mastra/auth'
import type { JwtPayload } from '@mastra/auth'

type MyUser = JwtPayload

interface MyJwksAuthOptions extends MastraAuthProviderOptions<MyUser> {
jwksUri?: string
issuer?: string
}

export class MyJwksAuth extends MastraAuthProvider<MyUser> {
protected jwksUri: string
protected issuer: string

constructor(options?: MyJwksAuthOptions) {
super({ name: options?.name ?? 'my-jwks-auth' })

const jwksUri = options?.jwksUri ?? process.env.MY_JWKS_URI
const issuer = options?.issuer ?? process.env.MY_AUTH_ISSUER

if (!jwksUri) {
throw new Error('JWKS URI is required')
}

this.jwksUri = jwksUri
this.issuer = issuer ?? ''

this.registerOptions(options)
}

async authenticateToken(token: string): Promise<MyUser | null> {
try {
const payload = await verifyJwks(token, this.jwksUri)

// Optionally validate issuer
if (this.issuer && payload.iss !== this.issuer) {
return null
}

return payload
} catch {
return null
}
}

async authorizeUser(user: MyUser): Promise<boolean> {
// Check token hasn't expired
if (user.exp && user.exp * 1000 < Date.now()) {
return false
}
return !!user.sub
}
}

自訂授權邏輯
自訂授權邏輯 的直接連結

提供自訂 authorizeUser 函數以覆寫預設授權邏輯:

const auth = new MyAuthProvider({
apiUrl: process.env.MY_AUTH_API_URL,
apiKey: process.env.MY_AUTH_API_KEY,

// Custom authorization: require admin role for all requests
async authorizeUser(user, request) {
return user.roles.includes('admin')
},
})

以角色為基礎的授權
以角色為基礎的授權 的直接連結

const auth = new MyAuthProvider({
async authorizeUser(user, request) {
const path = request.url
const method = request.method

// Admin routes require admin role
if (path.startsWith('/admin/')) {
return user.roles.includes('admin')
}

// Write operations require write role
if (['POST', 'PUT', 'PATCH', 'DELETE'].includes(method)) {
return user.roles.includes('write') || user.roles.includes('admin')
}

// Read operations allowed for all authenticated users
return true
},
})

測試自訂驗證 Provider
測試自訂驗證 Provider 的直接連結

使用 Vitest 的測試結構範例:

import { describe, it, expect, vi, beforeEach } from 'vitest'
import { MyAuthProvider } from './my-auth-provider'

// Mock fetch for API calls
global.fetch = vi.fn()

describe('MyAuthProvider', () => {
const mockOptions = {
apiUrl: 'https://auth.example.com',
apiKey: 'test-api-key',
}

beforeEach(() => {
vi.clearAllMocks()
})

describe('initialization', () => {
it('should initialize with provided options', () => {
const auth = new MyAuthProvider(mockOptions)
expect(auth).toBeInstanceOf(MyAuthProvider)
})

it('should throw error when required options are missing', () => {
expect(() => new MyAuthProvider({})).toThrow('Auth API URL and API key are required')
})
})

describe('authenticateToken', () => {
it('should return user when token is valid', async () => {
const mockUser = { id: 'user123', email: 'test@example.com', roles: ['read'] }
;(fetch as any).mockResolvedValue({
ok: true,
json: () => Promise.resolve(mockUser),
})

const auth = new MyAuthProvider(mockOptions)
const result = await auth.authenticateToken('valid-token', {} as any)

expect(fetch).toHaveBeenCalledWith(
'https://auth.example.com/verify',
expect.objectContaining({
method: 'POST',
body: JSON.stringify({ token: 'valid-token' }),
}),
)
expect(result).toEqual(mockUser)
})

it('should return null when token is invalid', async () => {
;(fetch as any).mockResolvedValue({ ok: false })

const auth = new MyAuthProvider(mockOptions)
const result = await auth.authenticateToken('invalid-token', {} as any)

expect(result).toBeNull()
})
})

describe('authorizeUser', () => {
it('should return true when user has valid id', async () => {
const auth = new MyAuthProvider(mockOptions)
const result = await auth.authorizeUser(
{ id: 'user123', email: 'test@example.com', roles: [] },
{} as any,
)

expect(result).toBe(true)
})

it('should return false when user has no id', async () => {
const auth = new MyAuthProvider(mockOptions)
const result = await auth.authorizeUser(
{ id: '', email: 'test@example.com', roles: [] },
{} as any,
)

expect(result).toBe(false)
})
})

describe('custom authorization', () => {
it('should use custom authorizeUser when provided', async () => {
const auth = new MyAuthProvider({
...mockOptions,
authorizeUser: user => user.roles.includes('admin'),
})

const adminUser = { id: 'user123', email: 'admin@example.com', roles: ['admin'] }
const regularUser = { id: 'user456', email: 'user@example.com', roles: ['read'] }

expect(await auth.authorizeUser(adminUser, {} as any)).toBe(true)
expect(await auth.authorizeUser(regularUser, {} as any)).toBe(false)
})
})

describe('route configuration', () => {
it('should store public routes configuration', () => {
const publicRoutes = ['/health', '/api/status']
const auth = new MyAuthProvider({
...mockOptions,
public: publicRoutes,
})

expect(auth.public).toEqual(publicRoutes)
})

it('should store protected routes configuration', () => {
const protectedRoutes = ['/api/*', '/admin/*']
const auth = new MyAuthProvider({
...mockOptions,
protected: protectedRoutes,
})

expect(auth.protected).toEqual(protectedRoutes)
})
})
})

錯誤處理
錯誤處理 的直接連結

為常見失敗情況提供清晰的錯誤訊息:

export class MyAuthProvider extends MastraAuthProvider<MyUser> {
constructor(options?: MyAuthOptions) {
super({ name: options?.name ?? 'my-auth' })

const apiUrl = options?.apiUrl ?? process.env.MY_AUTH_API_URL
const apiKey = options?.apiKey ?? process.env.MY_AUTH_API_KEY

if (!apiUrl) {
throw new Error(
'Missing MY_AUTH_API_URL. Set the environment variable or pass apiUrl in options.',
)
}

if (!apiKey) {
throw new Error(
'Missing MY_AUTH_API_KEY. Set the environment variable or pass apiKey in options.',
)
}

this.apiUrl = apiUrl
this.apiKey = apiKey
this.registerOptions(options)
}

async authenticateToken(token: string): Promise<MyUser | null> {
if (!token || typeof token !== 'string') {
return null // Immediate safe fail
}

try {
const response = await fetch(`${this.apiUrl}/verify`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-API-Key': this.apiKey,
},
body: JSON.stringify({ token }),
})

if (!response.ok) {
return null
}

return await response.json()
} catch (error) {
// Log error for debugging, but don't expose details to client
console.error('Auth verification error:', error)
return null
}
}
}

內置 Provider
內置 Provider 的直接連結

Mastra 包含以下驗證 Provider,可用作參考實作:

  • MastraJwtAuth:使用 HMAC secret 的簡單 JWT 驗證(@mastra/auth
  • MastraAuthClerk:Clerk 驗證(@mastra/auth-clerk
  • MastraAuthAuth0:Auth0 驗證(@mastra/auth-auth0
  • MastraAuthSupabase:Supabase 驗證(@mastra/auth-supabase
  • MastraAuthFirebase:Firebase 驗證(@mastra/auth-firebase
  • MastraAuthWorkOS:WorkOS 驗證(@mastra/auth-workos
  • MastraAuthBetterAuth:Better Auth 整合(@mastra/auth-better-auth
  • SimpleAuth:用於開發的 token 至用戶映射(@mastra/core/server

如需實作詳情,請參閱原始碼