> Discover all available pages from the documentation index: https://mastra.zisheng.pro/zh-TW/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-TW/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}`, }, }) } ``` > **資訊:** Access token 在 Authorization header 中必須以 `Bearer` 為前綴。 > > 如需更多設定選項,請參閱 [Mastra Client SDK](https://mastra.zisheng.pro/zh-TW/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 && (
Result:
{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" }' ```