Custom auth provider
自定义认证提供方允许你为内置提供方未覆盖的身份系统实现认证。扩展 MastraAuthProvider 基类即可集成任意认证系统。
概览概览的直接链接
认证提供方负责处理传入请求的认证和授权:
- Token 校验和用户提取
- 用户授权逻辑
- 基于路径的访问控制(公开/受保护路由)
创建自定义认证提供方以支持:
- 自托管身份系统
- 自定义 Token 格式或校验逻辑
- 专用授权规则
- 企业 SSO 集成
创建自定义认证提供方创建自定义认证提供方的直接链接
扩展 MastraAuthProvider 类并实现必需的方法:
import { MastraAuthProvider } from '@mastra/core/server'
import type { MastraAuthProviderOptions, MastraAuthRequest } from '@mastra/core/server'
// 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: MastraAuthRequest): 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: MastraAuthRequest): Promise<boolean> {
// Basic authorization: user must exist and have an ID
return !!user?.id
}
}
必需的方法必需的方法的直接链接
authenticateToken()authenticatetoken的直接链接
校验传入的 Token,如果有效则返回用户对象,如果认证失败则返回 null。
async authenticateToken(token: string, request: MastraAuthRequest): Promise<TUser | null>
| 参数 | 类型 | 描述 |
|---|---|---|
token | string | 从 Authorization 请求头中提取的 Bearer Token |
request | MastraAuthRequest | 传入的请求。使用 getRequestHeader() 读取请求头,使用 getWebRequest() 读取底层 Web Request,两者均从 @mastra/core/server 导出 |
返回:认证成功时返回用户对象,失败时返回 null。
Token 会自动从 Authorization: Bearer <token> 请求头中提取。如果你需要访问其他请求头或 Cookie,请使用 request 参数。
authorizeUser()authorizeuser的直接链接
判断已认证用户是否有权访问该资源。
async authorizeUser(user: TUser, request: MastraAuthRequest): Promise<boolean> | boolean
| 参数 | 类型 | 描述 |
|---|---|---|
user | TUser | authenticateToken 返回的用户对象 |
request | MastraAuthRequest | 传入的请求 |
返回:true 表示允许访问,false 表示拒绝(返回 403 Forbidden)。
配置选项配置选项的直接链接
MastraAuthProviderOptions 接口支持以下选项:
| 选项 | 类型 | 描述 |
|---|---|---|
name | string | 用于日志/调试的提供方名称 |
authorizeUser | (user, request) => Promise<boolean> | boolean | 自定义授权函数 |
protected | (RegExp | string | [string, Methods | Methods[]])[] | 需要认证的路径 |
public | (RegExp | string | [string, Methods | Methods[]])[] | 绕过认证的路径,除非路由设置了 requiresAuth: true |
路径模式路径模式的直接链接
使用模式匹配配置哪些路径需要认证:
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
],
})
使用你的认证提供方使用你的认证提供方的直接链接
将自定义认证提供方注册到 Mastra 实例:
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 的提供方示例:基于 JWKS 的提供方的直接链接
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')
},
})
基于角色的授权基于角色的授权的直接链接
import { getWebRequest } from '@mastra/core/server'
const auth = new MyAuthProvider({
async authorizeUser(user, request) {
const webRequest = getWebRequest(request)
if (!webRequest) {
return false
}
const path = new URL(webRequest.url).pathname
const method = webRequest.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
},
})
测试自定义认证提供方测试自定义认证提供方的直接链接
使用 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
}
}
}
内置提供方内置提供方的直接链接
Mastra 包含以下认证提供方作为参考实现:
- MastraJwtAuth:基于 HMAC 密钥的简单 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)
有关实现细节,请参阅源代码。
相关内容相关内容的直接链接
- 认证概览:认证概念与配置
- 自定义 API 路由:控制自定义端点的认证