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

如何在Firebase Authentication中限制仅公司域名邮箱登录?

Alright, let's break down how to solve this problem properly. Since your database rules can't cover the Firebase Functions → external database flow, we need to enforce the @cat.com domain restriction at two critical layers: Firebase Authentication itself, and directly within your Cloud Functions. Here's a step-by-step approach:

1. Block non-cat.com users at the Firebase Auth level

First, we want to make sure users with non-cat.com emails can't even create valid accounts. Firebase Auth doesn't have a built-in setting for this, but we can use a Cloud Function trigger to automatically delete unauthorized users right after they sign up:

  • Head to your Firebase Console → Authentication → Sign-in method, and make sure Email/Password (or any other sign-in methods you're using) are enabled.
  • Create a Cloud Function that triggers when a new user is created. In this function, check if the user's email ends with @cat.com—if not, delete their account immediately. Here's the code:
const functions = require("firebase-functions");
const admin = require("firebase-admin");
admin.initializeApp();

exports.blockNonCatDomainUsers = functions.auth.user().onCreate(async (user) => {
  const userEmail = user.email;
  // Only proceed if the email exists and doesn't match our allowed domain
  if (userEmail && !userEmail.endsWith("@cat.com")) {
    await admin.auth().deleteUser(user.uid);
    functions.logger.info(`Removed unauthorized user: ${userEmail}`);
  }
});

This stops unauthorized accounts from being created in the first place, closing a potential entry point.

2. Validate the user domain in your data-fetching Cloud Functions

Since your Functions are the bridge between the dashboard and your external database, this is where the most critical check needs to happen. Every Function that serves dashboard data must verify the authenticated user's email domain before accessing the external database.

exports.fetchDashboardData = functions.https.onCall(async (data, context) => {
  // First, check if the user is authenticated
  if (!context.auth) {
    throw new functions.https.HttpsError(
      "unauthenticated",
      "You must be logged in to access this data."
    );
  }

  // Check if the user's email is from @cat.com
  const userEmail = context.auth.token.email;
  if (!userEmail.endsWith("@cat.com")) {
    throw new functions.https.HttpsError(
      "permission-denied",
      "Only users with @cat.com emails are allowed access."
    );
  }

  // Now fetch data from your external database
  const externalData = await yourExternalDatabaseFetchLogic();
  return externalData;
});

For HTTP Trigger Functions:

If you're using regular HTTP endpoints instead of callable functions, you'll need to manually verify the Firebase ID token from the request headers:

exports.fetchDashboardData = functions.https.onRequest(async (req, res) => {
  // Extract the ID token from the Authorization header
  const idToken = req.headers.authorization?.split("Bearer ")[1];
  if (!idToken) {
    return res.status(401).send("Unauthorized: No token provided.");
  }

  try {
    // Verify the token is valid
    const decodedToken = await admin.auth().verifyIdToken(idToken);
    const userEmail = decodedToken.email;

    // Check the domain restriction
    if (!userEmail.endsWith("@cat.com")) {
      return res.status(403).send("Permission Denied: Only @cat.com users are allowed.");
    }

    // Fetch and return the external data
    const externalData = await yourExternalDatabaseFetchLogic();
    res.status(200).send(externalData);
  } catch (error) {
    return res.status(401).send("Unauthorized: Invalid token.");
  }
});

This ensures that even if an unauthorized user somehow slips past the Auth-level check (a rare edge case), they can't get any data through your Functions.

3. Add front-end validation (optional but user-friendly)

While server-side checks are non-negotiable for security, adding a front-end check gives users immediate feedback before they even attempt to sign in. For example, in your login form:

// Example React login handler
const handleLoginSubmit = async (email, password) => {
  if (!email.endsWith("@cat.com")) {
    alert("Only @cat.com email addresses are allowed to log in.");
    return;
  }
  // Proceed with Firebase Auth sign-in
  try {
    await signInWithEmailAndPassword(auth, email, password);
    // Redirect to dashboard
  } catch (error) {
    // Handle login errors
  }
};

Remember: this is just for UX, not security—never rely solely on front-end checks.

Quick Key Reminders
  • Always prioritize server-side checks: Front-end code can be modified, so Auth triggers and Function validations are your real security barrier.
  • If you use other sign-in providers (like Google), extend the Auth onCreate function to check their email domains too—same logic applies.
  • Double-check your Cloud Function permissions: the default service account should have permission to delete users, but if you run into issues, verify IAM settings in the Firebase Console.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 15:17:29