跳至主要內容

JSON Web Token

MastraJwtAuth 類別使用 JSON Web Token(JWT),為 Mastra 提供輕量的身份驗證機制。它會根據共用密鑰驗證傳入的請求,並透過 auth 選項與 Mastra 伺服器整合。

安裝
安裝 的直接連結

使用 MastraJwtAuth 類別前,必須先安裝 @mastra/auth 依賴套件。

npm install @mastra/auth@latest

建立 JWT
建立 JWT 的直接連結

如要驗證傳送至 Mastra 伺服器的請求,你需要一個使用 MASTRA_JWT_SECRET 簽署的有效 JSON Web Token(JWT)。

最簡單的產生方式是使用 jwt.io

  1. 選擇 JWT Encoder
  2. 向下捲動至 Sign JWT: Secret 部分。
  3. 輸入你的密鑰(例如:supersecretdevkeythatishs256safe!)。
  4. 按一下 Generate example,建立有效的 JWT。
  5. 複製產生的 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> 作為值。

設定 MastraClient
configuring-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 快速進行本機測試:

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>
}