> Discover all available pages from the documentation index: https://mastra.zisheng.pro/zh-TW/llms.txt # JSON Web Token `MastraJwtAuth` 類別使用 JSON Web Token(JWT),為 Mastra 提供輕量的身分驗證機制。它會依據共用密鑰驗證傳入請求,並透過 `auth` 選項與 Mastra 伺服器整合。 ## 安裝 使用 `MastraJwtAuth` 類別前,必須先安裝 `@mastra/auth` 套件。 **npm**: ```bash npm install @mastra/auth@latest ``` **pnpm**: ```bash pnpm add @mastra/auth@latest ``` **Yarn**: ```bash yarn add @mastra/auth@latest ``` **Bun**: ```bash bun add @mastra/auth@latest ``` ## 建立 JWT 若要驗證傳送至 Mastra 伺服器的請求,你需要一個以 `MASTRA_JWT_SECRET` 簽署的有效 JSON Web Token(JWT)。 最簡單的產生方式是使用 [jwt.io](https://www.jwt.io/): 1. 選取 **JWT Encoder**。 2. 向下捲動至 **Sign JWT: Secret** 區段。 3. 輸入密鑰(例如:`supersecretdevkeythatishs256safe!`)。 4. 按一下 **Generate example** 以建立有效的 JWT。 5. 複製產生的權杖,並在 `.env` 檔案中將其設為 `MASTRA_JWT_TOKEN`。 ## 使用範例 使用產生的 JWT,在 Mastra 伺服器中設定 `MastraJwtAuth`: ```typescript import { Mastra } from '@mastra/core' import { MastraJwtAuth } from '@mastra/auth' export const mastra = new Mastra({ server: { auth: new MastraJwtAuth({ secret: process.env.MASTRA_JWT_SECRET, }), }, }) ``` 如需所有可用設定選項,請參閱 [MastraJwtAuth](https://mastra.zisheng.pro/zh-TW/reference/auth/jwt)。 在 [Studio](https://mastra.zisheng.pro/zh-TW/docs/studio/overview) 中前往 **Settings**,然後在 **Headers** 下選取 **"Add Header"** 按鈕。輸入 `Authorization` 作為標頭名稱,並輸入 `Bearer ` 作為值。 ## 設定 `MastraClient` 啟用 `auth` 後,透過 `MastraClient` 發出的所有請求都必須在 `Authorization` 標頭中包含有效的 JWT: ```typescript import { MastraClient } from '@mastra/client-js' export const mastraClient = new MastraClient({ baseUrl: 'https://', headers: { Authorization: `Bearer ${process.env.MASTRA_JWT_TOKEN}`, }, }) ``` 如需更多設定選項,請參閱 [Mastra Client SDK](https://mastra.zisheng.pro/zh-TW/docs/server/mastra-client)。 ### 發出已驗證的請求 設定 `MastraClient` 後,你可以從前端應用程式傳送已驗證的請求,或使用 `curl` 快速進行本機測試: **React**: ```tsx import { mastraClient } from '../../lib/mastra-client' export const TestAgent = () => { async function handleClick() { const agent = mastraClient.getAgent('weatherAgent') const response = await agent.generate('Weather in London') console.log(response) } return } ``` **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" }' ```