JSON Web Token
MastraJwtAuth 類別使用 JSON Web Token(JWT),為 Mastra 提供輕量的身分驗證機制。它會依據共用密鑰驗證傳入請求,並透過 auth 選項與 Mastra 伺服器整合。
安裝「安裝」的直接連結
使用 MastraJwtAuth 類別前,必須先安裝 @mastra/auth 套件。
- npm
- pnpm
- Yarn
- Bun
npm install @mastra/auth@latest
pnpm add @mastra/auth@latest
yarn add @mastra/auth@latest
bun add @mastra/auth@latest
建立 JWT「建立 JWT」的直接連結
若要驗證傳送至 Mastra 伺服器的請求,你需要一個以 MASTRA_JWT_SECRET 簽署的有效 JSON Web Token(JWT)。
最簡單的產生方式是使用 jwt.io:
- 選取 JWT Encoder。
- 向下捲動至 Sign JWT: Secret 區段。
- 輸入密鑰(例如:
supersecretdevkeythatishs256safe!)。 - 按一下 Generate example 以建立有效的 JWT。
- 複製產生的權杖,並在
.env檔案中將其設為MASTRA_JWT_TOKEN。
使用範例「使用範例」的直接連結
使用產生的 JWT,在 Mastra 伺服器中設定 MastraJwtAuth:
src/mastra/index.ts
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。
在 Studio 中前往 Settings,然後在 Headers 下選取 "Add Header" 按鈕。輸入 Authorization 作為標頭名稱,並輸入 Bearer <your-jwt> 作為值。
設定 MastraClient「configuring-mastraclient」的直接連結
啟用 auth 後,透過 MastraClient 發出的所有請求都必須在 Authorization 標頭中包含有效的 JWT:
lib/mastra/mastra-client.ts
import { MastraClient } from '@mastra/client-js'
export const mastraClient = new MastraClient({
baseUrl: 'https://<mastra-api-url>',
headers: {
Authorization: `Bearer ${process.env.MASTRA_JWT_TOKEN}`,
},
})
如需更多設定選項,請參閱 Mastra Client SDK。
發出已驗證的請求「發出已驗證的請求」的直接連結
設定 MastraClient 後,你可以從前端應用程式傳送已驗證的請求,或使用 curl 快速進行本機測試:
- React
- cURL
src/components/test-agent.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 <button onClick={handleClick}>Test Agent</button>
}
curl -X POST http://localhost:4111/api/agents/weatherAgent/generate \
-H "Content-Type: application/json" \
-H "Authorization: Bearer <your-jwt>" \
-d '{
"messages": "Weather in London"
}'