> Discover all available pages from the documentation index: https://mastra.zisheng.pro/ko/llms.txt # 중포 기지 그만큼`@mastra/auth-firebase`패키지는 Firebase 인증을 사용하여 Mastra에 대한 인증을 제공합니다. Firebase ID 토큰을 사용하여 들어오는 요청을 확인하고 다음을 사용하여 Mastra 서버와 통합합니다.`auth`옵션. ## 전제조건 이 예에서는 Firebase 인증을 사용합니다. 다음을 확인하세요. 1. 다음에서 Firebase 프로젝트를 만듭니다.[Firebase Console](https://console.firebase.google.com/) 2. 인증을 활성화하고 선호하는 로그인 방법(Google, 이메일/비밀번호 등)을 구성하세요. 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) ``` > **노트:** 서비스 계정 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`)가 설정되어 있으면 생성자 인수 없이 `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` 클래스는 생성자 옵션이나 환경 변수를 통해 구성할 수 있습니다. ### 환경변수 - `FIREBASE_SERVICE_ACCOUNT`: Firebase 서비스 계정 JSON 파일의 경로 - `FIRESTORE_DATABASE_ID`또는`FIREBASE_DATABASE_ID`: Firestore database ID > **노트:** 생성자 옵션을 제공하지 않으면 클래스가 이러한 환경 변수를 자동으로 읽습니다. 따라서 환경 변수가 올바르게 구성되어 있다면 인수 없이 `new MastraAuthFirebase()`를 호출할 수 있습니다. ### 사용자 인증 기본적으로 `MastraAuthFirebase`는 Firestore를 사용하여 사용자 액세스를 관리합니다. 사용자 UID를 키로 사용하는 문서가 포함된 `user_access` 컬렉션이 필요합니다. 이 컬렉션에 문서가 있는지에 따라 사용자의 권한 부여 여부가 결정됩니다. ```text user_access/ {user_uid_1}/ // Document exists = user authorized {user_uid_2}/ // Document exists = user authorized ``` 사용자 인증을 맞춤설정하려면 맞춤 설정을 제공하세요.`authorizeUser` function: ```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/ko/reference/auth/firebase)를 참조하세요. ## 클라이언트 측 설정 Firebase 인증을 사용하는 경우 클라이언트 측에서 Firebase를 초기화하고, 사용자를 인증하고, ID 토큰을 검색하여 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() ``` ### 사용자 인증 및 토큰 검색 Firebase 인증을 사용하여 사용자를 로그인하고 ID 토큰을 검색합니다. ```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` 헤더에 유효한 Firebase ID 토큰을 포함해야 합니다. ```typescript import { MastraClient } from '@mastra/client-js' export const createMastraClient = (idToken: string) => { return new MastraClient({ baseUrl: 'https://', headers: { Authorization: `Bearer ${idToken}`, }, }) } ``` > **정보:** Authorization 헤더의 ID 토큰 앞에는 `Bearer`를 붙여야 합니다. 더 많은 구성 옵션은 [Mastra Client SDK](https://mastra.zisheng.pro/ko/docs/server/mastra-client)를 참조하세요. ### 인증된 요청 만들기 Firebase ID 토큰으로 `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" }' ```