@mastra/core
Version:
Mastra is a framework for building AI-powered applications and agents with a modern TypeScript stack.
174 lines (134 loc) • 4.6 kB
Markdown
# 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.
```typescript
import { SimpleAuth } from '@mastra/core/server'
```
## Usage example
```typescript
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
| Option | Type | Required | Description |
| --------------- | ---------------------------- | -------- | -------------------------------------- |
| `tokens` | `Record<string, TUser>` | Yes | Map of tokens to user objects |
| `headers` | `string \| string[]` | No | Additional headers to check for tokens |
| `name` | `string` | No | Provider name for logging |
| `authorizeUser` | `(user, request) => boolean` | No | Custom authorization function |
| `protected` | `(RegExp \| string)[]` | No | Paths that require authentication |
| `public` | `(RegExp \| string)[]` | No | Paths 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:
```typescript
new SimpleAuth({
tokens: {
/* ... */
},
headers: ['X-API-Key', 'X-Custom-Auth'],
})
```
## Making authenticated requests
Include your token in the `Authorization` header:
```bash
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:
```bash
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:
```typescript
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:
```typescript
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:
```typescript
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](https://mastra.ai/docs/server/auth/jwt), [Clerk](https://mastra.ai/docs/server/auth/clerk), [Auth0](https://mastra.ai/docs/server/auth/auth0), or another identity provider.