Firebase允许含@符号的任意内容注册的技术问题咨询
Great question! By default, Firebase Authentication only validates that an email follows basic syntax rules (like having an @ symbol and a domain), which is why it accepts those obviously fake but syntactically correct emails. To restrict this, you have a few solid options depending on how strict you want to be:
1. Enforce Email Verification (Quick Win)
The simplest way to ensure users have access to the email they register with is to enable Firebase's built-in email verification. This requires users to click a link sent to their email address before they can sign in to your app.
How to set it up:
- Go to your Firebase Console → Authentication → Settings → General.
- Under "Email verification", toggle on "Enable email verification".
Code to send verification email (after user creation):
When a user signs up, trigger the verification email immediately:
// After creating a user with createUserWithEmailAndPassword user.sendEmailVerification() .then(() => { // Notify user to check their email for verification link }) .catch((error) => { // Handle any errors sending the email });
You can also restrict access to your app's resources until the email is verified using security rules. For example, in Firestore:
match /collection/{doc} { allow read, write: if request.auth != null && request.auth.token.email_verified; }
2. Add Client-Side Validation (Basic Filtering)
Before sending the registration request to Firebase, add client-side checks to filter out obviously fake emails. While this can be bypassed by malicious users, it stops casual fake registrations.
Examples of checks:
- Use a regex to ensure the email has a reasonable local part (avoid overly long random strings) and a valid top-level domain (like
.com,.org, etc.). - Block known disposable email domains (like
temp-mail.org,10minutemail.com) by maintaining a list and checking against it.
Sample regex for basic validation (adjust as needed):
const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/; if (!emailRegex.test(userEmail)) { // Show error message to the user }
3. Server-Side Validation with Firebase Functions (Strict Control)
For the most robust solution, use Firebase Cloud Functions to validate emails when a user is created. This runs on Firebase's servers, so it can't be bypassed. You can:
- Check if the email's domain has valid MX records (to ensure it's a real, deliverable domain).
- Cross-reference the email domain against a list of disposable email providers.
Example Function to Validate User Emails:
const functions = require("firebase-functions"); const admin = require("firebase-admin"); admin.initializeApp(); const dns = require("dns").promises; exports.validateUserEmail = functions.auth.user().onCreate(async (user) => { const email = user.email; const domain = email.split("@")[1]; try { // Check if domain has MX records (indicates it can receive emails) const mxRecords = await dns.resolveMx(domain); if (mxRecords.length === 0) { // No MX records = invalid domain, delete the user await admin.auth().deleteUser(user.uid); functions.logger.log(`Deleted user ${user.uid} with invalid domain: ${domain}`); } // Optional: Block disposable email domains const disposableDomains = new Set(["temp-mail.org", "10minutemail.com", "guerrillamail.com"]); if (disposableDomains.has(domain)) { await admin.auth().deleteUser(user.uid); functions.logger.log(`Deleted user ${user.uid} with disposable email: ${email}`); } } catch (error) { functions.logger.error(`Error validating email ${email}:`, error); // If DNS lookup fails (e.g., domain doesn't exist), delete the user await admin.auth().deleteUser(user.uid); } });
4. Combine Methods for Best Results
For most apps, combining email verification with server-side domain checks is ideal. It ensures users can only access your app if they control a real email address, while also blocking disposable or non-existent domains upfront.
内容的提问来源于stack exchange,提问作者Cameron L

