跳到主要内容
非官方简体中文翻译,内容版权归 Mastra 所有,遵循 Apache-2.0 许可。

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
配置-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>
}
On this page