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。
- 複製產生的 token,並在
.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 作為 header 名稱,並輸入 Bearer <your-jwt> 作為值。
設定 MastraClientconfiguring-mastraclient 的直接連結
啟用 auth 後,所有透過 MastraClient 發出的請求都必須在 Authorization header 中包含有效的 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"
}'