Firebase
@mastra/auth-firebase 套件使用 Firebase Authentication 為 Mastra 提供身份驗證。它會使用 Firebase ID token 驗證傳入的請求,並透過 auth 選項與 Mastra 伺服器整合。
先決條件先決條件 的直接連結
此範例使用 Firebase Authentication。請確保完成以下步驟:
- 在 Firebase Console 建立 Firebase 項目
- 啟用 Authentication,並設定你偏好的登入方式(Google、電郵/密碼等)
- 在 Project Settings > Service Accounts 產生服務帳戶金鑰
- 下載服務帳戶 JSON 文件
FIREBASE_SERVICE_ACCOUNT=/path/to/your/service-account-key.json
FIRESTORE_DATABASE_ID=(default)
# Alternative environment variable names:
# FIREBASE_DATABASE_ID=(default)
請妥善保管服務帳戶 JSON 文件,切勿將其提交至版本控制系統。
安裝安裝 的直接連結
使用 MastraAuthFirebase 類別前,必須先安裝 @mastra/auth-firebase 套件。
- npm
- pnpm
- Yarn
- Bun
npm install @mastra/auth-firebase@latest
pnpm add @mastra/auth-firebase@latest
yarn add @mastra/auth-firebase@latest
bun add @mastra/auth-firebase@latest
使用範例使用範例 的直接連結
使用環境變數的基本用法使用環境變數的基本用法 的直接連結
如果已設定所需的環境變數(FIREBASE_SERVICE_ACCOUNT 和 FIRESTORE_DATABASE_ID),即可在不傳入任何建構函數引數的情況下初始化 MastraAuthFirebase。此類別會自動讀取這些環境變數作為設定:
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(),
},
})
自訂設定自訂設定 的直接連結
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 類別。
環境變數環境變數 的直接連結
FIREBASE_SERVICE_ACCOUNT:Firebase 服務帳戶 JSON 文件的路徑FIRESTORE_DATABASE_ID或FIREBASE_DATABASE_ID:Firestore 資料庫 ID
如果未提供建構函數選項,此類別會自動讀取這些環境變數。因此,只要環境變數設定正確,即可在不傳入任何引數的情況下呼叫 new MastraAuthFirebase()。
使用者授權使用者授權 的直接連結
預設情況下,MastraAuthFirebase 使用 Firestore 管理使用者存取權限。它要求有一個 user_access 集合,當中的文件以使用者 UID 作為鍵。使用者是否獲得授權,取決於此集合內是否存在相應文件。
user_access/
{user_uid_1}/ // Document exists = user authorized
{user_uid_2}/ // Document exists = user authorized
如要自訂使用者授權,請提供自訂的 authorizeUser 函數:
import { MastraAuthFirebase } from '@mastra/auth-firebase'
const firebaseAuth = new MastraAuthFirebase({
authorizeUser: async user => {
// Custom authorization logic
return user.email?.endsWith('@yourcompany.com') || false
},
})
請參閱 MastraAuthFirebase,了解所有可用的設定選項。
用戶端設定用戶端設定 的直接連結
使用 Firebase 身份驗證時,你需要在用戶端初始化 Firebase、驗證使用者身份,並擷取其 ID token,再將 token 傳送至 Mastra 請求。
在用戶端設定 Firebase在用戶端設定 Firebase 的直接連結
首先,在用戶端應用程式中初始化 Firebase:
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驗證使用者身份並擷取 token 的直接連結
使用 Firebase Authentication 讓使用者登入並擷取其 ID token:
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 文檔。
設定 MastraClientconfiguring-mastraclient 的直接連結
啟用 auth 後,所有透過 MastraClient 發出的請求都必須在 Authorization header 中包含有效的 Firebase ID token:
import { MastraClient } from '@mastra/client-js'
export const createMastraClient = (idToken: string) => {
return new MastraClient({
baseUrl: 'https://<mastra-api-url>',
headers: {
Authorization: `Bearer ${idToken}`,
},
})
}
在 Authorization header 中,ID token 前面必須加上 Bearer。
請參閱 Mastra Client SDK,了解更多設定選項。
發出已驗證身份的請求發出已驗證身份的請求 的直接連結
使用 Firebase ID token 設定 MastraClient 後,即可傳送已驗證身份的請求:
- React
- Node.js
- cURL
'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>
)
}
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 -X POST http://localhost:4111/api/agents/weatherAgent/generate \
-H "Content-Type: application/json" \
-H "Authorization: Bearer <your-firebase-id-token>" \
-d '{
"messages": "Weather in London"
}'