> Discover all available pages from the documentation index: https://mastra.zisheng.pro/llms.txt
# Auth0
`@mastra/auth-auth0` 包使用 Auth0 为 Mastra 提供身份验证。它使用 Auth0 签发的 JWT 令牌验证传入请求,并通过 `auth` 选项与 Mastra 服务器集成。
## 前置条件
本示例使用 Auth0 身份验证。请确保:
1. 在 [auth0.com](https://auth0.com/) 创建 Auth0 账户
2. 在 Auth0 Dashboard 中设置 Application
3. 在 Auth0 Dashboard 中配置 API,并设置标识符(audience)
4. 配置应用允许的回调 URL、Web 来源和注销 URL
```env
AUTH0_DOMAIN=your-tenant.auth0.com
AUTH0_AUDIENCE=your-api-identifier
```
> **备注:** 可以在 Auth0 Dashboard 的 Applications > Settings 下找到域名。audience 是在 Auth0 Dashboard > APIs 中配置的 API 标识符。
>
> 有关详细设置说明,请参阅适用于相应平台的 [Auth0 快速入门](https://auth0.com/docs/quickstarts)。
## 安装
在使用 `MastraAuthAuth0` 类之前,必须安装 `@mastra/auth-auth0` 包。
**npm**:
```bash
npm install @mastra/auth-auth0@latest
```
**pnpm**:
```bash
pnpm add @mastra/auth-auth0@latest
```
**Yarn**:
```bash
yarn add @mastra/auth-auth0@latest
```
**Bun**:
```bash
bun add @mastra/auth-auth0@latest
```
## 用法示例
### 使用环境变量的基本用法
```typescript
import { Mastra } from '@mastra/core'
import { MastraAuthAuth0 } from '@mastra/auth-auth0'
export const mastra = new Mastra({
server: {
auth: new MastraAuthAuth0(),
},
})
```
### 自定义配置
```typescript
import { Mastra } from '@mastra/core'
import { MastraAuthAuth0 } from '@mastra/auth-auth0'
export const mastra = new Mastra({
server: {
auth: new MastraAuthAuth0({
domain: process.env.AUTH0_DOMAIN,
audience: process.env.AUTH0_AUDIENCE,
}),
},
})
```
## 配置
### 用户授权
默认情况下,`MastraAuthAuth0` 允许所有持有指定 audience 的有效 Auth0 令牌且已通过身份验证的用户。令牌验证会确保:
1. 令牌由 Auth0 正确签名
2. 令牌尚未过期
3. 令牌 audience 与配置的 audience 匹配
4. 令牌签发者与 Auth0 域名匹配
要自定义用户授权,请提供自定义 `authorizeUser` 函数:
```typescript
import { MastraAuthAuth0 } from '@mastra/auth-auth0'
const auth0Provider = new MastraAuthAuth0({
authorizeUser: async user => {
// Custom authorization logic
return user.email?.endsWith('@yourcompany.com') || false
},
})
```
有关所有可用配置选项,请参阅 [MastraAuthAuth0](https://mastra.zisheng.pro/reference/auth/auth0)。
## 客户端设置
使用 Auth0 身份验证时,需要设置 Auth0 React SDK、对用户进行身份验证,并获取访问令牌以传递给 Mastra 请求。
### 设置 Auth0 React SDK
首先,在应用中安装并配置 Auth0 React SDK:
**npm**:
```bash
npm install @auth0/auth0-react
```
**pnpm**:
```bash
pnpm add @auth0/auth0-react
```
**Yarn**:
```bash
yarn add @auth0/auth0-react
```
**Bun**:
```bash
bun add @auth0/auth0-react
```
```typescript
import React from 'react'
import { Auth0Provider } from '@auth0/auth0-react'
const Auth0ProviderWithHistory = ({ children }) => {
return (
{children}
)
}
export default Auth0ProviderWithHistory
```
### 获取访问令牌
使用 Auth0 React SDK 对用户进行身份验证并获取访问令牌:
```typescript
import { useAuth0 } from '@auth0/auth0-react'
export const useAuth0Token = () => {
const { getAccessTokenSilently } = useAuth0()
const getAccessToken = async () => {
const token = await getAccessTokenSilently()
return token
}
return { getAccessToken }
}
```
> **备注:** 有关更多身份验证方法和配置选项,请参阅 [Auth0 React SDK 文档](https://auth0.com/docs/libraries/auth0-react)。
## 配置 `MastraClient`
启用 `auth` 后,使用 `MastraClient` 发出的所有请求都必须在 `Authorization` 标头中包含有效的 Auth0 访问令牌:
```typescript
import { MastraClient } from '@mastra/client-js'
export const createMastraClient = (accessToken: string) => {
return new MastraClient({
baseUrl: 'https://',
headers: {
Authorization: `Bearer ${accessToken}`,
},
})
}
```
> **信息:** 访问令牌在 Authorization 标头中必须带有 `Bearer` 前缀。
>
> 有关更多配置选项,请参阅 [Mastra Client SDK](https://mastra.zisheng.pro/docs/server/mastra-client)。
### 发出经过身份验证的请求
使用 Auth0 访问令牌配置 `MastraClient` 后,即可发送经过身份验证的请求:
**React**:
```tsx
import React, { useState } from 'react'
import { useAuth0 } from '@auth0/auth0-react'
import { MastraClient } from '@mastra/client-js'
export const MastraApiTest = () => {
const { getAccessTokenSilently } = useAuth0()
const [result, setResult] = useState(null)
const callMastraApi = async () => {
const token = await getAccessTokenSilently()
const mastra = new MastraClient({
baseUrl: 'http://localhost:4111',
headers: {
Authorization: `Bearer ${token}`,
},
})
const weatherAgent = mastra.getAgent('weatherAgent')
const response = await weatherAgent.generate("What's the weather like in New York")
setResult(response.text)
}
return (
{result && (
)}
)
}
```
**cURL**:
```bash
curl -X POST http://localhost:4111/api/agents/weatherAgent/generate \
-H "Content-Type: application/json" \
-H "Authorization: Bearer " \
-d '{
"messages": "Weather in London"
}'
```