Simple Auth

Trust: ★★★☆☆ (0.90) · 0 validations · developer_reference

Published: 2026-05-10 · Source: crawler_authoritative

Tình huống

Mastra Agent SDK guide for configuring SimpleAuth token-based authentication for local development, testing, and basic API key scenarios.

Insight

The SimpleAuth class provides token-based authentication using a basic token-to-user mapping. It is included in @mastra/core/server and supports configuration options including: tokens (Record<string, TUser> - required), headers (string | string[] - custom headers to check), name (string - provider name for logging), authorizeUser (function for custom authorization), protected (paths requiring auth), and public (paths bypassing auth). Default headers checked are Authorization (with or without Bearer prefix) and X-Playground-Access. Custom headers can be added via the headers option. The authorizeUser callback receives (user, request) parameters and can implement role-based logic by checking request.url. Limitations include: tokens stored in memory, no token expiration or refresh, no cryptographic verification, and all tokens must be known at startup.

Hành động

Import SimpleAuth from ‘@mastra/core/server’. Define a User type with id, name, and role properties. Create a Mastra instance with server.auth configured to a new SimpleAuth instance. Pass a tokens object mapping token strings to user objects. For custom authorization, provide an authorizeUser callback that receives the authenticated user and request object, returning boolean for access control. Make authenticated requests by including the token in the Authorization header, either with or without the Bearer prefix. For environment-based tokens, load from process.env at startup and populate the tokens object conditionally. To use with MastraClient, pass the Authorization header in the client constructor.

Kết quả

Returns the mapped user object for validated tokens via the authorizeUser callback; protected paths return 401 for invalid/missing tokens.

Điều kiện áp dụng

SimpleAuth is included in @mastra/core with no additional packages required. Not suitable for production use.


Nội dung gốc (Original)

Simple Auth

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

Use cases

  • Local development and testing
  • Simple API key authentication
  • Prototyping before integrating a full identity provider
  • Internal services with static tokens

Installation

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

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

Usage example

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

Configuration options

OptionTypeRequiredDescription
tokensRecord<string, TUser>YesMap of tokens to user objects
headersstring | string[]NoAdditional headers to check for tokens
namestringNoProvider name for logging
authorizeUser(user, request) => booleanNoCustom authorization function
protected(RegExp | string)[]NoPaths that require authentication
public(RegExp | string)[]NoPaths that bypass authentication

Default Headers

SimpleAuth checks these headers by default:

  • Authorization (with or without Bearer prefix)
  • X-Playground-Access

Add custom headers using the headers option:

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

Making authenticated requests

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"}'

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"}'

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

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

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

Limitations

SimpleAuth is designed for simplicity, not production security:

  • Tokens are stored in memory
  • No token expiration or refresh
  • No cryptographic verification
  • All tokens must be known at startup

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

Liên kết

Xem thêm: