Skip to main content

MastraAuthFirebase 类

🌐 MastraAuthFirebase Class

MastraAuthFirebase 类使用 Firebase 认证为 Mastra 提供身份验证。它通过 Firebase ID 令牌验证传入请求,并使用 auth 选项与 Mastra 服务器集成。

🌐 The MastraAuthFirebase class provides authentication for Mastra using Firebase Authentication. It verifies incoming requests using Firebase ID tokens and integrates with the Mastra server using the auth option.

先决条件
Direct link to 先决条件

🌐 Prerequisites

此示例使用 Firebase 身份验证。请确保:

🌐 This example uses Firebase Authentication. Make sure to:

  1. Firebase 控制台 创建一个 Firebase 项目
  2. 启用身份验证并配置你偏好的登录方式(谷歌、邮箱/密码等)
  3. 在项目设置 > 服务账户中生成服务账户密钥
  4. 下载服务账号 JSON 文件
.env
FIREBASE_SERVICE_ACCOUNT=/path/to/your/service-account-key.json
FIRESTORE_DATABASE_ID=(default)
# Alternative environment variable names:
# FIREBASE_DATABASE_ID=(default)
note

请将你的服务账户 JSON 文件安全地存储,并且绝不要将其提交到版本控制中。

🌐 Store your service account JSON file securely and never commit it to version control.

安装
Direct link to 安装

🌐 Installation

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

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

npm install @mastra/auth-firebase@latest

用法示例
Direct link to 用法示例

🌐 Usage examples

使用环境变量的基本用法
Direct link to 使用环境变量的基本用法

🌐 Basic usage with environment variables

如果你设置了所需的环境变量(FIREBASE_SERVICE_ACCOUNTFIRESTORE_DATABASE_ID),你可以在不提供任何构造函数参数的情况下初始化 MastraAuthFirebase。该类会自动读取这些环境变量作为配置:

🌐 If you set the required environment variables (FIREBASE_SERVICE_ACCOUNT and FIRESTORE_DATABASE_ID), you can initialize MastraAuthFirebase without any constructor arguments. The class will automatically read these environment variables as configuration:

src/mastra/index.ts
import { Mastra } from "@mastra/core";
import { MastraAuthFirebase } from "@mastra/auth-firebase";

// Automatically uses FIREBASE_SERVICE_ACCOUNT and FIRESTORE_DATABASE_ID env vars
export const mastra = new Mastra({
server: {
auth: new MastraAuthFirebase(),
},
});

自定义配置
Direct link to 自定义配置

🌐 Custom configuration

src/mastra/index.ts
import { Mastra } from "@mastra/core";
import { MastraAuthFirebase } from "@mastra/auth-firebase";

export const mastra = new Mastra({
server: {
auth: new MastraAuthFirebase({
serviceAccount: "/path/to/service-account.json",
databaseId: "your-database-id",
}),
},
});

配置
Direct link to 配置

🌐 Configuration

MastraAuthFirebase 类可以通过构造函数选项或环境变量进行配置。

🌐 The MastraAuthFirebase class can be configured through constructor options or environment variables.

环境变量
Direct link to 环境变量

🌐 Environment Variables

  • FIREBASE_SERVICE_ACCOUNT:Firebase 服务账号 JSON 文件的路径
  • FIRESTORE_DATABASE_IDFIREBASE_DATABASE_ID:Firestore 数据库 ID
note

当未提供构造函数选项时,该类会自动读取这些环境变量。这意味着,如果你的环境变量已正确配置,你可以直接调用 new MastraAuthFirebase() 而无需任何参数。

🌐 When constructor options are not provided, the class automatically reads these environment variables. This means you can simply call new MastraAuthFirebase() without any arguments if your environment variables are properly configured.

用户授权
Direct link to 用户授权

🌐 User Authorization

默认情况下,MastraAuthFirebase 使用 Firestore 来管理用户访问。它期望有一个名为 user_access 的集合,集合中的文档以用户 UID 为键。该集合中文档的存在决定了用户是否被授权。

🌐 By default, MastraAuthFirebase uses Firestore to manage user access. It expects a collection named user_access with documents keyed by user UIDs. The presence of a document in this collection determines whether a user is authorized.

firestore-structure.txt
user_access/
{user_uid_1}/ // Document exists = user authorized
{user_uid_2}/ // Document exists = user authorized

要自定义用户权限,请提供一个自定义的 authorizeUser 函数:

🌐 To customize user authorization, provide a custom authorizeUser function:

src/mastra/auth.ts
import { MastraAuthFirebase } from "@mastra/auth-firebase";

const firebaseAuth = new MastraAuthFirebase({
authorizeUser: async (user) => {
// Custom authorization logic
return user.email?.endsWith("@yourcompany.com") || false;
},
});
info

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

🌐 Visit MastraAuthFirebase for all available configuration options.

客户端设置
Direct link to 客户端设置

🌐 Client-side setup

使用 Firebase 认证时,你需要在客户端初始化 Firebase、验证用户身份,并获取他们的 ID 令牌以传递给你的 Mastra 请求。

🌐 When using Firebase auth, you'll need to initialize Firebase on the client side, authenticate users, and retrieve their ID tokens to pass to your Mastra requests.

在客户端设置 Firebase
Direct link to 在客户端设置 Firebase

🌐 Setting up Firebase on the client

首先,在客户端应用中初始化 Firebase:

🌐 First, initialize Firebase in your client application:

lib/firebase.ts
import { initializeApp } from "firebase/app";
import { getAuth, GoogleAuthProvider } from "firebase/auth";

const firebaseConfig = {
apiKey: process.env.NEXT_PUBLIC_FIREBASE_API_KEY,
authDomain: process.env.NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN,
projectId: process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID,
};

const app = initializeApp(firebaseConfig);
export const auth = getAuth(app);
export const googleProvider = new GoogleAuthProvider();

验证用户并获取令牌
Direct link to 验证用户并获取令牌

🌐 Authenticating users and retrieving tokens

使用 Firebase 身份验证登录用户并获取他们的 ID 令牌:

🌐 Use Firebase authentication to sign in users and retrieve their ID tokens:

lib/auth.ts
import { signInWithPopup, signOut, User } from "firebase/auth";
import { auth, googleProvider } from "./firebase";

export const signInWithGoogle = async () => {
try {
const result = await signInWithPopup(auth, googleProvider);
return result.user;
} catch (error) {
console.error("Error signing in:", error);
throw error;
}
};

export const getIdToken = async (user: User) => {
try {
const idToken = await user.getIdToken();
return idToken;
} catch (error) {
console.error("Error getting ID token:", error);
throw error;
}
};

export const signOutUser = async () => {
try {
await signOut(auth);
} catch (error) {
console.error("Error signing out:", error);
throw error;
}
};
note

有关其他身份验证方法,如电子邮件/密码、手机验证等,请参阅 Firebase 文档

🌐 Refer to the Firebase documentation for other authentication methods like email/password, phone authentication, and more.

配置 MastraClient
Direct link to configuring-mastraclient

🌐 Configuring MastraClient

当启用 auth 时,所有使用 MastraClient 发出的请求必须在 Authorization 头中包含有效的 Firebase ID 令牌:

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

lib/mastra/mastra-client.ts
import { MastraClient } from "@mastra/client-js";

export const createMastraClient = (idToken: string) => {
return new MastraClient({
baseUrl: "https://<mastra-api-url>",
headers: {
Authorization: `Bearer ${idToken}`,
},
});
};
info

在 Authorization 头中,ID 令牌必须以 Bearer 为前缀。

🌐 The ID token must be prefixed with Bearer in the Authorization header.

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

🌐 Visit Mastra Client SDK for more configuration options.

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

🌐 Making authenticated requests

一旦 MastraClient 配置了 Firebase ID 令牌,你就可以发送经过身份验证的请求:

🌐 Once MastraClient is configured with the Firebase ID token, you can send authenticated requests:

src/components/test-agent.tsx
"use client";

import { useAuthState } from 'react-firebase-hooks/auth';
import { MastraClient } from "@mastra/client-js";
import { auth } from '../lib/firebase';
import { getIdToken } from '../lib/auth';

export const TestAgent = () => {
const [user] = useAuthState(auth);

async function handleClick() {
if (!user) return;

const token = await getIdToken(user);
const client = createMastraClient(token);

const weatherAgent = client.getAgent("weatherAgent");
const response = await weatherAgent.generate("What's the weather like in New York");

console.log({ response });
}

return (
<button onClick={handleClick} disabled={!user}>
Test Agent
</button>
);
};