一个用户刚在Firebase(网页版)创建账号时没有任何权限,为什么?

A user doesn't have any persmission when its account has just been created in Firebase (web version), why?

我正在尝试在 Web 项目中使用 Firebase(使用 NextJS),但这是我的问题:用户没有帐户,因此帐户自然是使用 createUserWithEmailAndPassword() 创建的。但是,我想在创建帐户后立即将数据存储在 Firestore 中……这就是问题所在。事实上 Firebase 会抛出以下错误:

FirebaseError: [code=permission-denied]: Missing or insufficient permissions.

这是我的代码的摘录:

import { useState } from "react";
import {
  createUserWithEmailAndPassword,
  getAuth,
} from "firebase/auth";
import {
  collection,
  getFirestore,
  addDoc,
} from "firebase/firestore";

export const ConnectionPage = () => {
  // the values of the inputs in the HTML content
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");

  // the function executed when the user clicks the register button
  const submit = async (e) => {
    e.preventDefault();
    // create a new user with email and password
    // and add the document in the "users" collection
    try {
      const userCredentials = await createUserWithEmailAndPassword(
        getAuth(),
        email,
        password
      );
      const user = userCredentials.user;
      const userInfo = {
        uid: user.uid,
        // ...and all kind of data
      };
      const collectionRef = collection(getFirestore(), "users");
      // my problem starts here
      // the following line will throw an error
      // "[code=permission-denied]: Missing or insufficient permissions."
      // whereas, according to the rules in Firestore, it should work
      // because I just ask the user to be authenticated (`allow write, read: if request.auth != null`)
      // and according to the documentation, `createUserWithEmailAndPassword` logs in the user.
      const docRef = await addDoc(collectionRef, userInfo);
      console.log(`New document with id '${docRef.id}' created successfully.`);
    } catch (e) {
      console.error("An error has occured during register, look:");
      console.error(e.toString());
    }
  };

  // returns a form
  // with an email input
  // and a password input
  // and a button to register
};

这是我在 Firestore 中的规则:

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow write, read: if request.auth != null;
    }
  }
}

请帮助我,我能找到的解决类似问题的唯一方法是在创建帐户后注销用户,然后立即登录。

我试过了:

当你刚刚拥有:

allow read;

这是一个完整的声明,意味着没有人可以读取数据。

如果要对读和写应用相同的条件,请使用:

allow read, write: if request.auth != null;

尝试在创建帐户时使用 auth state observer 而不是 await。根据我的经验,创建帐户后不会立即设置当前用户对象,您必须等到身份验证状态观察器触发非空用户对象才能执行经过身份验证的查询。如果没有非空的 currentUser,需要身份验证的 Firestore 查询将失败。

import { getAuth, onAuthStateChanged } from "firebase/auth";

const auth = getAuth();
onAuthStateChanged(auth, (user) => {
  if (user) {
    // User is signed in, see docs for a list of available properties
    // https://firebase.google.com/docs/reference/js/firebase.User
    const uid = user.uid;
    // ...
  } else {
    // User is signed out
    // ...
  }
});

如果您觉得这是一个错误,那么我建议在 GitHub 上提交它。

由于我在 GitHub 中与贡献者交谈,问题已解决。问题来自 App Check 功能,该功能在版本 9.6.0.

之前不适用于 Firestore

解决方法是:

npm install firebase@9.6.0

默认情况下,npm install firebase 安装版本 9.5.0

请注意,此版本是最新版本,如果您在 2031 年看到该消息,它就完全没用了。

感谢回答我的人:)