我得到了错误

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());
             }
         }
     });

当前回答

转到Apple Certificates, Identifiers & Profiles: 选择您的密钥上传firebase并进行检查: 访问DeviceCheck和apptest api以获取您关联的数据

在这里输入图像描述

其他回答

对我来说,问题是AppCheck在我的Firestore控制台也被激活了。 所以我必须按照指南中所述的应用程序检查颤振指南

https://firebase.google.com/docs/app-check/flutter/debug-provider?hl=it&authuser=0

打开androidDebugProvider: true,从控制台复制调试令牌,并将其粘贴到Firestore部分(AppCheck—> app—> add调试令牌),它立即工作。

转到Apple Certificates, Identifiers & Profiles: 选择您的密钥上传firebase并进行检查: 访问DeviceCheck和apptest api以获取您关联的数据

在这里输入图像描述

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

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;
}

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

所以在我的情况下,我有以下DB规则:

service cloud.firestore {
  match /databases/{database}/documents {
    match /stories/{story} {
      function isSignedIn() {
        return request.auth.uid != null;
      }
    
      allow read, write: if isSignedIn() && request.auth.uid == resource.data.uid
    }
  }
}

正如您所看到的,故事文档上有一个uid字段用来标记所有者。

然后在我的代码中,我查询了所有的故事(Flutter):

Firestore.instance
          .collection('stories')
          .snapshots()

它失败了,因为我已经通过不同的用户添加了一些故事。 要解决这个问题,你需要在查询中添加条件:

Firestore.instance
          .collection('stories')
          .where('uid', isEqualTo: user.uid)
          .snapshots()

更多详情请访问:https://firebase.google.com/docs/firestore/security/rules-query

编辑:从链接

规则不是过滤器 在编写检索文档的查询时,请保持 请记住,安全规则不是过滤器—查询都是或 什么都没有。为了节省您的时间和资源,Cloud Firestore会评估一个 根据其潜在结果集而不是实际字段查询 所有文档的值。查询是否可能返回 客户端没有权限读取的文档,全部删除 请求失败。

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

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

它也是区分大小写的。

希望这对大家有所帮助