> Discover all available pages from the documentation index: https://mastra.zisheng.pro/zh-HK/llms.txt
# Auth0
`@mastra/auth-auth0` 套件使用 Auth0 為 Mastra 提供身份驗證。它會使用 Auth0 簽發的 JWT token 驗證傳入的請求,並透過 `auth` 選項與 Mastra 伺服器整合。
## 先決條件
此範例使用 Auth0 身份驗證。請確保你已:
1. 在 [auth0.com](https://auth0.com/) 建立 Auth0 帳戶
2. 在 Auth0 Dashboard 設定 Application
3. 在 Auth0 Dashboard 設定 API,並指定識別碼(audience)
4. 設定應用程式允許的 callback URL、web origin 及 logout URL
```env
AUTH0_DOMAIN=your-tenant.auth0.com
AUTH0_AUDIENCE=your-api-identifier
```
> **備註:** 你可以在 Auth0 Dashboard 的 Applications > Settings 下找到你的 domain。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 token,並已通過身份驗證的使用者存取。Token 驗證會確保:
1. Token 已由 Auth0 正確簽署
2. Token 尚未過期
3. Token 的 audience 與你設定的 audience 相符
4. Token 的 issuer 與你的 Auth0 domain 相符
如要自訂使用者授權,請提供自訂的 `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/zh-HK/reference/auth/auth0),了解所有可用的設定選項。
## 客戶端設定
使用 Auth0 身份驗證時,你需要設定 Auth0 React SDK、驗證使用者身份,並取得其 access token,以傳送至你的 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
```
### 取得 access token
使用 Auth0 React SDK 驗證使用者身份並取得其 access token:
```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` header 中包含有效的 Auth0 access token:
```typescript
import { MastraClient } from '@mastra/client-js'
export const createMastraClient = (accessToken: string) => {
return new MastraClient({
baseUrl: 'https://',
headers: {
Authorization: `Bearer ${accessToken}`,
},
})
}
```
> **資訊:** 在 Authorization header 中,access token 前面必須加上 `Bearer`。
>
> 請瀏覽 [Mastra Client SDK](https://mastra.zisheng.pro/zh-HK/docs/server/mastra-client),了解更多設定選項。
### 發出已驗證身份的請求
使用 Auth0 access token 設定 `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"
}'
```