Firebase
@mastra/auth-firebase 套件透過 Firebase Authentication 為 Mastra 提供驗證功能。它會使用 Firebase ID token 驗證傳入的請求,並透過 auth 選項與 Mastra 伺服器整合。
事前準備「事前準備」的直接連結
此範例使用 Firebase Authentication。請務必完成下列事項:
- 在 Firebase Console 中建立 Firebase 專案
- 啟用 Authentication,並設定偏好的登入方式(Google、電子郵件/密碼等)
- 從 Project Settings > Service Accounts 產生 service account key
- 下載 service account JSON 檔案
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
- 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),你可以不傳入任何 constructor 引數來初始化 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 類別可透過 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,會決定使用者是否獲得授權。
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 以傳入 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 文件。
設定 MastraClient「configuring-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}`,
},
})
}
ID token 在 Authorization header 中必須以 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"
}'