firestore:PERMISSION_DENIED:权限缺失或不足

firestore: PERMISSION_DENIED: Missing or insufficient permissions

我遇到错误

gettingdocuments.com.google.firebase.firestore.FirebaseFirestoreException: PERMISSION_DENIED: Missing or insufficient permissions.

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

进入数据库 -> 规则 ->

开发用:

allow read, write: if false; 更改为 true;

Note: It's quick solution for development purpose only because it will turns off all the security. So, it's not recommended for production.

用于生产:

如果从 firebase 进行身份验证:Change allow read, write: if false;request.auth != null;

确保您的数据库不为空,也确保您查询的是不存在的集合

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

例如,firebase 上的集合名称是 users,但您使用 db.collection("Users")db.collection("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;
    }
  }
}

所以在我的例子中,我有以下数据库规则:

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

如您所见,story 文档中有一个 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

编辑:来自 link

Rules are not filters When writing queries to retrieve documents, keep in mind that security rules are not filters—queries are all or nothing. To save you time and resources, Cloud Firestore evaluates a query against its potential result set instead of the actual field values for all of your documents. If a query could potentially return documents that the client does not have permission to read, the entire request fails.

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

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

如果您在 Java Swing 应用程序中尝试。

  1. 转到 Firebase Console > Project Overview > Project Settings

  2. 然后转到“服务帐户”选项卡,然后单击“生成新私钥”。

  3. 你会得到一个.json文件,把它放在一个已知的路径

  4. 然后转到我的电脑属性、高级系统设置、环境变量。

  5. 创建新的路径变量 GOOGLE_APPLICATION_CREDENTIALS 值为 json 文件的路径。

npm i --save firebase @angular/fire

在 app.module 确保你导入

import { AngularFireModule } from '@angular/fire';
import { AngularFirestoreModule } from '@angular/fire/firestore';

进口

AngularFireModule.initializeApp(environment.firebase),
    AngularFirestoreModule,
    AngularFireAuthModule,

实时数据库规则确保您有

{
  /* Visit  rules. */
  "rules": {
    ".read": true,
    ".write": true
  }
}

在云 Firestore 规则中确保您有

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

检查是否在 IAM & Admin https://console.cloud.google.com/iam-admin/iam 中添加了具有适当角色的服务帐户,例如 Editor

https://console.firebase.google.com

开发->数据库->规则->设置读写->true

问题是您试图在用户通过身份验证之前将数据读取或写入实时数据库或 Firestore。请尝试检查代码的范围。 希望对您有所帮助!

我在使用 Firebase Admin 时遇到了这个错误,解决方案是正确配置 Firebase Admin following this link

对于这种情况,你的规则应该是这样的,但是消息说这不是建议的方式,但如果你这样做,你可以在没有权限的情况下插入错误

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read, write;
    }
  }
}

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

我通过在 GCP 的 IAM 设置中授予服务帐户 Service Account User 角色以及 Cloud Datastore User 角色解决了这个问题。

对我来说,这是日期的问题。已更新,问题已解决。

允许 read/write:

 if request.time < timestamp.date(2020, 5, 21);

编辑:如果您仍然感到困惑并且无法找出问题所在,请查看您的 firebase 控制台中的规则部分。

此时,2020 年 6 月, 默认情况下,firebase 是按时间定义的。 定义满足您需求的时间。

allow read, write: if request.time < timestamp.date(2020, 7, 10);

请注意:您的数据库仍然对任何人开放。我建议,请阅读文档并以对您有用的方式配置数据库。

时间限制可能已过

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {

    // This rule allows anyone on the internet to view, edit, and delete
    // all data in your Firestore database. It is useful for getting
    // started, but it is configured to expire after 30 days because it
    // leaves your app open to attackers. At that time, all client
    // requests to your Firestore database will be denied.
    //
    // Make sure to write security rules for your app before that time, or else
    // your app will lose access to your Firestore database
    match /{document=**} {
      allow read, write: if request.time < timestamp.date(2020,7, 1);
    }
  }
}

这一行更改日期

 allow read, write: if request.time < timestamp.date(2020,7, 1);

GO to rules in firebase and edit rules ..... (provide a timestamp or set to false) My solution.

service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read, write: if request.time < timestamp.date(2021, 8, 18);
    }
  }
}

我在指定安全规则后也遇到了“权限缺失或不足”的错误。事实证明,默认情况下规则 不是递归的 !即如果你写了一个像

这样的规则
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;
}

relevant section of the documentation 阅读更多内容。

转到 firebase 控制台 => 云 firestore 数据库并添加允许用户读写的规则。

=> 允许读、写

进入 Firestore 数据库 > 规则:

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

更多信息:https://firebase.google.com/docs/rules/rules-language?authuser=0

目前 100% 工作!

也许您需要删除日期

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read, write: if
          request.time < timestamp.date(2021, 12, 12);
    }
  }
}

转到 Apple 证书、标识符和配置文件: Select 您的密钥上传 firebase 并检查: 访问 DeviceCheck 和 AppAttest API 以获取关联的数据

enter image description here

在此处更改
将 false 设置为 true

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

并发布新规则

我已经设法解决了我的问题。 我有 2 个错误:

  1. PERMISSION_DENIED: 权限缺失或不足。
  2. 无法为此项目启用 Firestore。

解决此问题的步骤:

第 1 部分。

  1. 转到https://console.firebase.google.com/
  2. Firestore 数据库 -> 删除所有集合
  3. Firestore 数据库 -> 规则 -> 删除所有规则历史记录

第 2 部分。

  1. 前往https://console.cloud.google.com/
  2. 在菜单中查找:APIs & Services -> Enabled APIs & Services
  3. 禁用 3 项服务:“Cloud Firestore API”、“Firebase Rules API”、“Cloud Storage for Firebase API”
  4. 在菜单中找到:Firestore -> 它将自动启用“Cloud Firestore API”和“Firebase Rules API”服务并创建 Firestore 数据库。
  5. 为 Firebase 启用“云存储 API”。

最重要的是从 Google Cloud Console 创建 Firestore 数据库。