You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

如何为Web应用直接在Firebase项目后端集成Google服务账号?

How to Integrate Google Service Accounts with Firebase Projects & Enable API Calls Without API Keys for Web Apps

Hey there, let's break down your two questions step by step—both are about leveraging Google service accounts with Firebase, so I'll make sure to keep things practical and actionable.

1. Integrating a Google Service Account Directly into Your Firebase Project

A Google service account acts as your backend's "identity" to access Firebase services with admin-level permissions. Here's how to set it up properly:

  • Head to the Firebase Console, open your project, and click the gear icon (Project Settings) in the left sidebar.
  • Switch to the Service Accounts tab.
  • Under the "Firebase Admin SDK" section, click Generate New Private Key. Confirm the prompt, and a JSON file (e.g., service-account-key.json) will download to your machine.
  • Configure the key based on your environment:
    • Local/self-hosted servers: Set the GOOGLE_APPLICATION_CREDENTIALS environment variable to point to your JSON file. On Linux/macOS, run this in your terminal:
      export GOOGLE_APPLICATION_CREDENTIALS="/full/path/to/service-account-key.json"
      
      On Windows, add the variable via System Properties > Environment Variables.
    • Firebase Cloud Functions: No manual config needed—Cloud Functions runs in Google's environment and automatically inherits the project's service account permissions (you can customize this if needed during deployment).
    • Admin SDK initialization in code: You can also load the key directly in your backend code. For Node.js:
      const admin = require('firebase-admin');
      const serviceAccount = require('./service-account-key.json');
      
      admin.initializeApp({
        credential: admin.credential.cert(serviceAccount)
      });
      
  • Critical note: Never commit this JSON key to version control (like Git) or expose it to frontend code—it contains sensitive credentials that could let someone take over your Firebase project.

2. Integrating the Service Account into Your Firebase Backend for Web Apps (No API Key Needed)

The core idea is to avoid exposing Firebase API keys in your frontend code by using your backend as a proxy. The frontend calls your backend endpoints, and the backend uses the service account to authenticate and interact with Firebase/Google APIs.

Step 1: Set Up the Backend with the Service Account

Follow the steps from the first question to configure the service account in your backend (e.g., Express server or Cloud Functions).

Step 2: Create a Proxy Endpoint

Let's use a Node.js Express server as an example. Here's how to build an endpoint that fetches Firestore data and returns it to the frontend:

const express = require('express');
const admin = require('firebase-admin');
const app = express();

// Initialize Firebase Admin SDK
const serviceAccount = require('./service-account-key.json');
admin.initializeApp({
  credential: admin.credential.cert(serviceAccount)
});

const db = admin.firestore();

// Proxy endpoint: frontend calls this instead of Firestore directly
app.get('/api/fetch-collection', async (req, res) => {
  try {
    // Fetch data using the service account (no API key needed here)
    const snapshot = await db.collection('your-target-collection').get();
    const data = snapshot.docs.map(doc => ({ id: doc.id, ...doc.data() }));
    
    res.status(200).json(data);
  } catch (error) {
    res.status(500).json({ error: 'Failed to fetch data' });
  }
});

app.listen(3000, () => console.log('Backend server running on port 3000'));

Step 3: Frontend Calls the Backend Endpoint

Your frontend can now fetch data using a simple HTTP request—no Firebase API key required:

// Frontend JavaScript example
async function loadData() {
  try {
    const response = await fetch('/api/fetch-collection');
    const data = await response.json();
    console.log('Data from backend:', data);
    // Render data in your UI
  } catch (error) {
    console.error('Error loading data:', error);
  }
}

Step 4: Secure the Endpoint (Important!)

Even without an API key, you need to ensure only authorized users can access your backend. Use Firebase Authentication to verify the user's ID token:

app.get('/api/fetch-collection', async (req, res) => {
  // Get the ID token from the request headers
  const idToken = req.headers.authorization?.split('Bearer ')[1];
  
  if (!idToken) {
    return res.status(401).json({ error: 'Unauthorized: No token provided' });
  }

  try {
    // Verify the token using the service account
    const decodedToken = await admin.auth().verifyIdToken(idToken);
    // Token is valid—proceed to fetch data
    const snapshot = await db.collection('your-target-collection').get();
    const data = snapshot.docs.map(doc => ({ id: doc.id, ...doc.data() }));
    
    res.status(200).json(data);
  } catch (error) {
    res.status(401).json({ error: 'Unauthorized: Invalid token' });
  }
});

On the frontend, include the user's ID token in the request headers after they log in:

async function loadData() {
  const user = firebase.auth().currentUser;
  const idToken = await user.getIdToken();
  
  try {
    const response = await fetch('/api/fetch-collection', {
      headers: {
        'Authorization': `Bearer ${idToken}`
      }
    });
    const data = await response.json();
    // Render data
  } catch (error) {
    console.error('Error loading data:', error);
  }
}

内容的提问来源于stack exchange,提问作者Harry

火山引擎 最新活动