You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何仅从自有域名/网页应用调用Firebase Cloud Functions?

Restricting Firebase Cloud Functions to Your Own Domain/Web App

Hey there! Great question—yes, you absolutely can lock down your Firebase Cloud Functions so they only respond to requests from your own web app or domain, blocking tools like Postman, curl, or other arbitrary API clients. Here are the most practical and reliable methods to pull this off:

1. Use Firebase App Check (Official, Most Secure)

Firebase App Check is Google's built-in solution to protect your backend resources from abuse by verifying that requests come from your legitimate app. For web apps, you'll use reCAPTCHA v3 under the hood:

  • Step 1: Enable App Check in the Firebase Console for your web app, and configure reCAPTCHA v3 (you'll get a site key and secret key).
  • Step 2: Add the App Check SDK to your frontend code, so every request to your Cloud Function includes an App Check token.
  • Step 3: In your Cloud Function, verify the token before processing the request. Here's a quick Node.js example:
    const admin = require('firebase-admin');
    admin.initializeApp();
    
    exports.yourFunction = functions.https.onRequest(async (req, res) => {
      const appCheckToken = req.headers['x-firebase-appcheck'];
      
      if (!appCheckToken) {
        res.status(401).send('Unauthorized: No App Check token provided');
        return;
      }
    
      try {
        await admin.appCheck().verifyToken(appCheckToken);
        // Token is valid—proceed with your function logic
        res.status(200).send('Success!');
      } catch (err) {
        res.status(401).send('Unauthorized: Invalid App Check token');
        return;
      }
    });
    

App Check is tough to bypass because reCAPTCHA v3 analyzes the client environment to detect automated tools.

2. Validate Origin/Referer Headers (Extra Layer of Protection)

While this isn't 100% foolproof (headers can be spoofed), it's a quick way to block most casual external requests. You can check where the request is coming from by inspecting the Origin or Referer headers:

exports.yourFunction = functions.https.onRequest((req, res) => {
  const allowedOrigins = ['https://your-domain.com', 'http://localhost:3000']; // Include dev env
  const origin = req.headers.origin || req.headers.referer;

  if (!origin || !allowedOrigins.some(allowed => origin.startsWith(allowed))) {
    res.status(403).send('Forbidden: Request from unauthorized origin');
    return;
  }

  // Proceed with function logic
  res.status(200).send('Success!');
});

Pair this with App Check for a stronger defense—don't rely on it alone.

3. Combine with Firebase Authentication (For User-Specific Functions)

If your functions are meant for authenticated users, you can require a valid Firebase Auth ID token alongside App Check. This ensures only logged-in users from your app can access the function:

exports.yourFunction = functions.https.onRequest(async (req, res) => {
  // First verify App Check token (as shown earlier)
  // Then verify Auth token
  const authToken = req.headers.authorization?.split('Bearer ')[1];
  
  if (!authToken) {
    res.status(401).send('Unauthorized: No Auth token provided');
    return;
  }

  try {
    const decodedToken = await admin.auth().verifyIdToken(authToken);
    // User is authenticated—proceed
    res.status(200).send(`Hello, ${decodedToken.uid}!`);
  } catch (err) {
    res.status(401).send('Unauthorized: Invalid Auth token');
    return;
  }
});

Key Notes

  • Always use App Check as your primary defense—it's the most robust method provided by Firebase.
  • Don't forget to allow your development environment (like localhost) in your checks so you can test locally.
  • For callable functions (not HTTP functions), App Check works even more seamlessly—you just enable it in the console, and the client SDK automatically attaches the token.

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 09:12:42