> Discover all available pages from the documentation index: https://mastra.zisheng.pro/zh-TW/llms.txt # Firebase `@mastra/auth-firebase` 套件透過 Firebase Authentication 為 Mastra 提供驗證功能。它會使用 Firebase ID token 驗證傳入的請求,並透過 `auth` 選項與 Mastra 伺服器整合。 ## 事前準備 此範例使用 Firebase Authentication。請務必完成下列事項: 1. 在 [Firebase Console](https://console.firebase.google.com/) 中建立 Firebase 專案 2. 啟用 Authentication,並設定偏好的登入方式(Google、電子郵件/密碼等) 3. 從 Project Settings > Service Accounts 產生 service account key 4. 下載 service account JSON 檔案 ```env FIREBASE_SERVICE_ACCOUNT=/path/to/your/service-account-key.json FIRESTORE_DATABASE_ID=(default) # Alternative environment variable names: # FIREBASE_DATABASE_ID=(default) ``` > **備註:** 請安全地儲存 service account JSON 檔案,切勿將其提交至版本控制系統。 ## 安裝 使用 `MastraAuthFirebase` 類別前,必須先安裝 `@mastra/auth-firebase` 套件。 **npm**: ```bash npm install @mastra/auth-firebase@latest ``` **pnpm**: ```bash pnpm add @mastra/auth-firebase@latest ``` **Yarn**: ```bash yarn add @mastra/auth-firebase@latest ``` **Bun**: ```bash bun add @mastra/auth-firebase@latest ``` ## 使用範例 ### 搭配環境變數的基本用法 如果已設定必要的環境變數(`FIREBASE_SERVICE_ACCOUNT` 與 `FIRESTORE_DATABASE_ID`),你可以不傳入任何 constructor 引數來初始化 `MastraAuthFirebase`。此類別會自動讀取這些環境變數作為設定: ```typescript 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(), }, }) ``` ### 自訂設定 ```typescript 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', }), }, }) ``` ## 設定 `MastraAuthFirebase` 類別可透過 constructor 選項或環境變數進行設定。 ### 環境變數 - `FIREBASE_SERVICE_ACCOUNT`:Firebase service account JSON 檔案的路徑 - `FIRESTORE_DATABASE_ID` 或 `FIREBASE_DATABASE_ID`:Firestore database ID > **備註:** 未提供 constructor 選項時,此類別會自動讀取這些環境變數。因此,只要正確設定環境變數,就能呼叫不帶任何引數的 `new MastraAuthFirebase()`。 ### 使用者授權 `MastraAuthFirebase` 預設使用 Firestore 管理使用者存取權。它預期有一個 `user_access` collection,其中的 document 以使用者 UID 作為 key。此 collection 中是否有相應 document,會決定使用者是否獲得授權。 ```text user_access/ {user_uid_1}/ // Document exists = user authorized {user_uid_2}/ // Document exists = user authorized ``` 若要自訂使用者授權,請提供自訂的 `authorizeUser` 函式: ```typescript import { MastraAuthFirebase } from '@mastra/auth-firebase' const firebaseAuth = new MastraAuthFirebase({ authorizeUser: async user => { // Custom authorization logic return user.email?.endsWith('@yourcompany.com') || false }, }) ``` 請參閱 [MastraAuthFirebase](https://mastra.zisheng.pro/zh-TW/reference/auth/firebase),瞭解所有可用的設定選項。 ## 用戶端設定 使用 Firebase 驗證時,你需要在用戶端初始化 Firebase、驗證使用者,並取得其 ID token 以傳入 Mastra 請求。 ### 在用戶端設定 Firebase 首先,在用戶端應用程式中初始化 Firebase: ```typescript 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() ``` ### 驗證使用者並取得 token 使用 Firebase Authentication 登入使用者並取得其 ID token: ```typescript 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 } } ``` > **備註:** 如需電子郵件/密碼、電話驗證等其他驗證方式,請參閱 [Firebase 文件](https://firebase.google.com/docs/auth)。 ## 設定 `MastraClient` 啟用 `auth` 後,所有透過 `MastraClient` 發出的請求都必須在 `Authorization` header 中包含有效的 Firebase ID token: ```typescript import { MastraClient } from '@mastra/client-js' export const createMastraClient = (idToken: string) => { return new MastraClient({ baseUrl: 'https://', headers: { Authorization: `Bearer ${idToken}`, }, }) } ``` > **資訊:** ID token 在 Authorization header 中必須以 `Bearer` 為前綴。 > > 如需更多設定選項,請參閱 [Mastra Client SDK](https://mastra.zisheng.pro/zh-TW/docs/server/mastra-client)。 ### 發出已驗證的請求 使用 Firebase ID token 設定 `MastraClient` 後,即可傳送已驗證的請求: **React**: ```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 ( ) } ``` **Node.js**: ```typescript const express = require('express') const admin = require('firebase-admin') const { MastraClient } = require('@mastra/client-js') // Initialize Firebase Admin admin.initializeApp({ credential: admin.credential.cert({ // Your service account credentials }), }) const app = express() app.use(express.json()) app.post('/generate', async (req, res) => { try { const { idToken } = req.body // Verify the token await admin.auth().verifyIdToken(idToken) const mastra = new MastraClient({ baseUrl: 'http://localhost:4111', headers: { Authorization: `Bearer ${idToken}`, }, }) const weatherAgent = mastra.getAgent('weatherAgent') const response = await weatherAgent.generate("What's the weather like in Nairobi") res.json({ response: response.text }) } catch (error) { res.status(401).json({ error: 'Unauthorized' }) } }) ``` **cURL**: ```bash curl -X POST http://localhost:4111/api/agents/weatherAgent/generate \ -H "Content-Type: application/json" \ -H "Authorization: Bearer " \ -d '{ "messages": "Weather in London" }' ```