跳到主要内容

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. 复制生成的令牌,并在 .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 快速进行本地测试:

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