我得到了错误

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

进入数据库-> 规则- - - >

发展:

更改允许读,写:如果为false;真正的;

注意:它只是用于开发目的的快速解决方案,因为它将关闭所有安全性。因此,不建议在生产中使用。

生产:

如果从firebase验证:更改允许读,写:如果为false;请求。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;
    }
  }
}

所以在我的情况下,我有以下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会评估一个 根据其潜在结果集而不是实际字段查询 所有文档的值。查询是否可能返回 客户端没有权限读取的文档,全部删除 请求失败。

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

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

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

进入Firebase控制台>项目概述>项目设置 然后转到服务帐户选项卡,然后单击生成新的私钥。 你会得到一个.json文件,把它放在一个已知的路径中 然后进入“我的电脑属性”、“高级系统设置”、“环境变量”。 创建新的路径变量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
  }
}

在云壁炉规则确保你有

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管理员,解决方案是配置Firebase管理员正确遵循这个链接

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

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

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

允许读/写:

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

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

此时,即2020年6月,默认情况下firebase是按时间定义的。 为满足自己的需要而安排好时间。

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

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

时间限制可能已过

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

转到firebase中的规则,编辑规则.....(提供时间戳或设置为false) 我的解决方案。

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

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

进入firebase控制台=>云firestore数据库,添加允许用户读写的规则。

=>允许读写

也许你该把日期去掉

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

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

在这里输入图像描述

这里的变化 将false设为true

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

并发布新的规则

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

PERMISSION_DENIED:缺少或权限不足。 不能为此项目启用Firestore。

修复此问题的步骤:

第1部分。

访问https://console.firebase.google.com/ Firestore Database ->删除所有集合 Firestore Database -> Rules ->删除所有规则历史记录

第2部分。

访问https://console.cloud.google.com/ 在菜单中找到:api和服务->已启用的api和服务 禁用3个服务:“云Firestore API”,“Firebase规则API”,“Firebase API的云存储” Firestore ->将自动启用“云Firestore API”和“Firebase规则API”服务,并将创建Firestore数据库。 启用“Firebase API的云存储”。

最重要的是从谷歌云控制台创建一个Firestore数据库。

另一个原因是AppCheck。我在一个新项目上启用了它(创建~ 2022年5月),但还没有完成集成步骤,导致“缺少或权限不足”错误。

要解决此问题,首先完成Firebase中AppCheck部分中列出的AppCheck设置步骤。我在我的web应用程序中使用了ReCAPTCHA提供者,你需要复制ReCAPTCHA公钥来在你的代码库中使用。

接下来,在你初始化firebase应用的任何地方添加AppCheck初始化代码。我的在React中是这样的:

  import { initializeAppCheck, ReCaptchaV3Provider } from 'firebase/app-check';

  // ......

  // Initialize Firebase
  const app = initializeApp(firebaseConfig);
  const analytics = getAnalytics(app);

  self['FIREBASE_APPCHECK_DEBUG_TOKEN'] = true;
  // Pass your reCAPTCHA v3 site key (public key) to activate(). Make sure this
  // key is the counterpart to the secret key you set in the Firebase console.
  initializeAppCheck(app, {
    provider: new ReCaptchaV3Provider('PASTE KEY HERE'),

    // Optional argument. If true, the SDK automatically refreshes App Check
    // tokens as needed.
    isTokenAutoRefreshEnabled: true,
  });

注意FIREBASE_APPCHECK_DEBUG_TOKEN行在浏览器控制台中打印了一个调试令牌,你需要将它复制回AppCheck下的Firebase控制台中以完成设置,之后你可以注释/删除该行。

这解决了我的问题。

进一步的信息:

https://firebase.google.com/docs/app-check/web/recaptcha-provider https://firebase.google.com/docs/app-check/web/debug-provider?authuser=0&hl=en

有很多很好的答案,但由于这是Firestore许可拒绝错误的顶级谷歌响应,我想我应该为初学者和新手添加一个答案。

为什么要设置安全规则?

如果您编写自己的后端,您将让用户向服务器请求一些东西,服务器将决定允许他们做什么。例如,您的服务器不允许user1删除user2的所有数据。

但是由于你的用户直接与Firebase交互,你不能真正信任你的用户发送给你的任何东西。例如,User1可以将删除请求中的用户id更改为'user2'。

Firestore安全规则是你告诉Firestore即你的后端服务器,谁被允许读取和写入什么数据。

Firestore团队的这个视频非常有用。

https://www.youtube.com/watch?v=eW5MdE3ZcAw

如果你遇到“权限缺失或权限不足”的错误,我强烈建议你在尝试其他任何东西之前观看完整的22分钟视频。

我从1/10到7/10理解了安全规则是如何工作的,以及为什么我只从这个视频中得到了错误。

入门指南也很有用,可以帮助回答视频中没有涵盖的问题。https://firebase.google.com/docs/firestore/security/get-started

原始代码:

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

修改代码:

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

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

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

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

经过批准的答案是非常危险的,因为任何人都可以在没有任何许可的情况下读取或写入您的数据库。我建议用这个。

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

这将允许授权人员写入数据库,而任何人都可以读取数据库,以防访问者访问网站。

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