Skip to main content

MastraJwtAuth 类

🌐 MastraJwtAuth Class

MastraJwtAuth 类为 Mastra 提供了一种轻量级的身份验证机制,使用 JSON Web Tokens (JWTs)。它基于共享密钥验证传入请求,并通过 auth 选项与 Mastra 服务器集成。

🌐 The MastraJwtAuth class provides a lightweight authentication mechanism for Mastra using JSON Web Tokens (JWTs). It verifies incoming requests based on a shared secret and integrates with the Mastra server using the auth option.

安装
Direct link to 安装

🌐 Installation

在使用 MastraJwtAuth 类之前,你必须先安装 @mastra/auth 包。

🌐 Before you can use the MastraJwtAuth class you have to install the @mastra/auth package.

npm install @mastra/auth@latest

使用示例
Direct link to 使用示例

🌐 Usage example

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,
}),
},
});
info

请访问 MastraJwtAuth 获取所有可用的配置选项。

🌐 Visit MastraJwtAuth for all available configuration options.

配置 MastraClient
Direct link to configuring-mastraclient

🌐 Configuring MastraClient

当启用 auth 时,所有使用 MastraClient 发起的请求都必须在 Authorization 头中包含有效的 JWT:

🌐 When auth is enabled, all requests made with MastraClient must include a valid JWT in the Authorization header:

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}`,
},
});
info

访问 Mastra Client SDK 以获取更多配置选项。

🌐 Visit Mastra Client SDK for more configuration options.

进行身份验证的请求
Direct link to 进行身份验证的请求

🌐 Making authenticated requests

一旦配置了 MastraClient,你就可以从前端应用发送已认证的请求,或使用 curl 进行快速的本地测试:

🌐 Once MastraClient is configured, you can send authenticated requests from your frontend application, or use curl for quick local testing:

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

创建 JWT
Direct link to 创建 JWT

🌐 Creating a JWT

要对你的 Mastra 服务器的请求进行身份验证,你需要一个使用你的 MASTRA_JWT_SECRET 签名的有效 JSON Web 令牌(JWT)。

🌐 To authenticate requests to your Mastra server, you'll need a valid JSON Web Token (JWT) signed with your MASTRA_JWT_SECRET.

生成一个的最简单方法是使用 jwt.io

🌐 The easiest way to generate one is using jwt.io:

  1. 选择 JWT 编码器
  2. 向下滚动到 签署 JWT:密钥 部分。
  3. 输入你的密钥(例如:supersecretdevkeythatishs256safe!)。
  4. 点击 生成示例 来创建一个有效的 JWT。
  5. 复制生成的令牌,并将其作为 MASTRA_JWT_TOKEN 设置在你的 .env 文件中。