我得到了错误

gettingdocuments.com.google.firebase.firestore.FirebaseFirestoreException: PERMISSION_DENIED:缺少或权限不足。

对于下面关于else语句的代码

db.collection("users")
    .get()
    .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
        @Override
        public void onComplete(@NonNull Task<QuerySnapshot> task) {
             if (task.isSuccessful()) {
                 for (DocumentSnapshot document : task.getResult()) {
                     s(document.getId() + " => " + document.getData());
                 }
             } else {
                 s("Error getting documents."+ task.getException());
             }
         }
     });

当前回答

如果有人登陆这里试图使用服务帐户访问Firestore:

我通过在GCP的IAM设置中授予Service - Account Cloud Datastore User角色之外的Service Account User角色解决了这个问题。

其他回答

进入数据库->规则:

然后更改如下规则

service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read, write: if false;
    }
  }
}

以下

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

经过几天的研究,我弄清楚了Firestore的请求安全规则。只有在用户的身份验证状态初始化并设置为!= null之后,在客户端发出请求时,Auth才有效。如果您的请求是(任何机会)在使用请求时请求数据服务器端。Auth != null作为规则,它将被拒绝。不确定是否有任何解决方案,但我会试着找到一个或想出一个。如果你们有任何想法,请留下评论。

在指定安全规则后,我还出现了“缺少或权限不足”错误。事实证明,默认情况下规则不是递归的!例如,如果你写了一个规则

match /users/{userId} {
  allow read, write: if request.auth != null && request.auth.uid == userId;
}

该规则将不适用于/users/{userId}下的任何子集合。这就是我犯错误的原因。

我通过指定规则来修复它:

match /users/{userId}/{document=**} {
  allow read, write: if request.auth != null && request.auth.uid == userId;
}

在文档的相关部分中阅读更多信息。

此外,如果您的代码中的集合引用与firebase上的集合名称不匹配,则可能会出现此错误。

例如,firebase上的集合名称是users,但您使用db.collection(" users ")或db.collection("user")引用它。

它也是区分大小写的。

希望这对大家有所帮助

以上投票的答案对数据库的健康是危险的。你仍然可以让你的数据库只用于读取而不用于写入:

  service cloud.firestore {
    match /databases/{database}/documents {
     match /{document=**} {
       allow read: if true;
       allow write: if false;
      }
   }
}