Firestore。PERMISSION_DENIED: 缺少或没有足够的权限

291 人关注

我得到的错误是

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());
    
5 个评论
Is the user logged in?
你在Firebase控制台的安全标签下设置了规则吗?
我的错误,我没有看到云火库的下降框。我只在实时数据库中检查。
android
firebase
google-cloud-firestore
SUHAS REKHU
SUHAS REKHU
发布于 2017-10-06
29 个回答
Luvnish Monga
Luvnish Monga
发布于 2022-01-04
已采纳
0 人赞同

Go in Database -> Rules ->

For development:

Change allow read, write: if 假的。 to true;

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

For production:

如果从Firebase认证。【替换代码1 假的。 to request.auth != null。

注意,它允许每个人在没有任何授权的情况下读、写你的数据库。
这是一个可怕的解决方案,这简直是在破坏安全。去读这个吧。 firebase.google.com/docs/firestore/security/get-started
正如@DuncanLuk所说,这是一个糟糕的解决方案。我甚至不会把它称为一个解决方案
最好的解决方案,可以真正快速启动。安全问题实际上可以在以后解决。
这不是一个解决方案。"我在安全规则方面有问题,让我们完全禁用它们吧!"
Md Nakibul Hassan
Md Nakibul Hassan
发布于 2022-01-04
0 人赞同

Go to 数据库 -> Rules :

然后改变以下规则

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

to below

service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read, write: if request.auth != null;
    
这是一个坏主意,这使得所有的文件都可以被任何认证的用户写入,甚至是属于其他用户的东西,那些只应该由管理员写入的东西,或者根本就不可能被写入。请保留第一段代码,因为它是对未执行的安全规则的一种防范。
请注意,如果你让人们注册(例如用谷歌SSO),他们将自动获得你的所有数据。
我想让我的认证用户(少数)访问所有的文件,所以这个配方对我来说是完美的。
rwozniak
rwozniak
发布于 2022-01-04
0 人赞同

因此,在我的案例中,我有以下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文件上有一个story字段,用于标记所有者。

然后在我的代码中,我在查询所有的故事(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

EDIT: from the link

规则不是过滤器 在编写检索文件的查询时,要记住安全规则不是过滤器 牢记,安全规则不是过滤器--查询是全部或没有的。 毫无意义。为了节省你的时间和资源,Cloud Firestore会根据潜在的结果集而不是实际的字段来评估一个 查询的潜在结果集,而不是所有文档的实际字段 而不是所有文档的实际字段值。如果一个查询有可能返回 客户端没有阅读权限的文件,整个请求就会失败。 请求失败。

什么是用户对象?
我得到 Invalid variable name: request request 应该是某个参数参数吗?
你的 .where('uid', isEqualTo: user.uid) 点刚刚解决了几个小时的问题。规则确实不是过滤器!
xji
xji
发布于 2022-01-04
0 人赞同

在指定安全规则后,我也出现了 "权限缺失或不足 "的错误。结果发现,这些规则是 not recursive 默认情况下是这样的!也就是说,如果你写了一条规则,如

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;

阅读更多内容请访问文件的相关部分.

Nadun Liyanage
Nadun Liyanage
发布于 2022-01-04
0 人赞同

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

  • Go To Firebase Console > Project Overview > Project Settings

  • 然后进入服务账户标签,然后点击生成新的私钥。

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

  • 然后转到 "我的电脑属性","高级系统设置","环境变量"。

  • 创建新的路径变量 【替换代码3用你的json文件的路径值。

  • 这也是我的问题,有关于这个问题的信息在 docs .
    Ssubrat Rrudra
    Ssubrat Rrudra
    发布于 2022-01-04
    0 人赞同

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

      service cloud.firestore {
        match /databases/{database}/documents {
         match /{document=**} {
           allow read: if true;
           allow write: if false;
        
    启用权限的正确方法是什么,但不是对所有人都适用?
    maxarndt
    maxarndt
    发布于 2022-01-04
    0 人赞同

    如果有人在这里登陆,试图用服务账户访问Firestore。

    我解决了这个问题,在GCP的IAM设置中,除了授予服务账户 Service Account User 的角色,还授予了 Cloud Datastore User 的角色。

    如果你的用户是一个服务账户,则不需要服务账户用户。
    Rasel Khan
    Rasel Khan
    发布于 2022-01-04
    0 人赞同

    在这里改变
    将假的设为真

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

    并公布新的规则

    meropis
    不要使用这种解决方案。它允许任何用户从你的水桶中读和写。
    brother isn't it on develop & testing purpose? and if you don't have any read or write permission then how could you use??
    替换代码0】允许任何人,无论是否经过认证,都可以从水桶中读取和写入。
    Anga
    Anga
    发布于 2022-01-04
    0 人赞同

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

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

    它也是区分大小写的。

    Hope this helps someone

    集合不是隐式创建的吗?在你的例子中,"Users "和 "user "集合会在被引用的时候被创建。
    Anga
    @DevTJ 当它是一个 add set 的请求时,你是正确的,但从问题来看,它是一个 get 的请求。我以前也遇到过这种情况
    M.Mar
    M.Mar
    发布于 2022-01-04
    0 人赞同

    npm i -save firebase @angular/fire

    在app.module中,确保你导入了

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

    in imports

    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;
        
    Richardd
    Richardd
    发布于 2022-01-04
    0 人赞同

    在这个时候,2020年6月。 默认情况下,Firebase是按时间定义的。 定义时间以满足你的需要。

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

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

    0 人赞同

    我在使用Firebase管理时遇到这个错误,解决办法是正确配置Firebase管理。 following this link

    Bilal Ahmad
    Bilal Ahmad
    发布于 2022-01-04
    0 人赞同

    Go in Firestore's Database > Rules:

    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%的工作!😬

    DozeStrawberry
    DozeStrawberry
    发布于 2022-01-04
    0 人赞同

    原始代码。

    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;
        
    itzhar
    itzhar
    发布于 2022-01-04
    0 人赞同

    确保你的数据库不是空的,你的查询是针对不存在的集合。

    这个异常与空集合或数据库无关,这是一个权限问题。
    Rehan Ali
    这个异常与空Db等没有关系。安全规则和授权的问题。
    Me & at least 3 others have this exception on this scenario. If it's not help you, move on to the next solution
    Pramendra Gupta
    Pramendra Gupta
    发布于 2022-01-04
    0 人赞同

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

    dova dominique kabengela
    dova dominique kabengela
    发布于 2022-01-04
    0 人赞同

    问题是,你试图在用户被验证之前向实时数据库或Firestore读取或写入数据,请尝试检查你代码的范围。 希望这对你有帮助!

    Söhrab Vahidli
    Söhrab Vahidli
    发布于 2022-01-04
    0 人赞同

    时间限制可能会超过

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

    there 更改日期为现在 in this line:

     allow read, write: if request.time < timestamp.date(2020,7, 1);
        
    titleLogin
    titleLogin
    发布于 2022-01-04
    0 人赞同

    也许你需要删除日期

    rules_version = '2';
    service cloud.firestore {
      match /databases/{database}/documents {
        match /{document=**} {
          allow read, write: if
              request.time < timestamp.date(2021, 12, 12);
        
    Joshua Dance
    Joshua Dance
    发布于 2022-01-04
    0 人赞同

    有很多很好的答案,但由于这是谷歌对Firestore权限拒绝错误的最高回应,我想我将为初学者和菜鸟添加一个答案。

    Why Security Rules?

    如果你写了你自己的后台,你会让用户向你的服务器要求什么,而服务器会决定他们被允许做什么。例如,你的服务器不会允许用户1删除用户2的所有数据。

    但是,由于你的用户是直接与Firebase交互的,你不能真正相信你的用户发给你的任何东西。比如说,用户1可以把他的删除请求中的用户ID改为 "用户2"。

    Firestore安全规则是你告诉Firestore(也就是你的后端服务器)谁可以读写什么数据的地方。

    来自Firestore团队的这段视频非常有帮助。

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

    如果你遇到 "权限缺失或不足 "的错误,我强烈建议你在尝试其他事情之前,先看完这段22分钟的视频。

    我对安全规则的工作原理的理解从1/10上升到7/10,仅从这段视频中就可以看出我为什么会出现错误。

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

    Giang
    Giang
    发布于 2022-01-04
    0 人赞同

    https://console.firebase.google.com

    Develop -> Database -> Rules -> set read, write -> true

    match /databases/{database}/documents { match /{document=**} { allow read, write: if request.time < timestamp.date(2021, 8, 18);
    IBoteju
    IBoteju
    发布于 2022-01-04
    0 人赞同

    Go to firebase console => cloud firestore database and add rule allowing users to read and write.

    => allow read, write

    0 人赞同

    在我的案例中,我已经成功地解决了这个问题。 我有2个错误。

  • PERMISSION_DENIED: Missing or insufficient permissions.
  • Cannot enable Firestore for this project.
  • Steps to fix this issue:

    第一部分。

  • Go to the https://console.firebase.google.com/
  • Firestore Database -> Delete all collections
  • Firestore Database -> Rules -> Delete all rules history
  • 第二部分。

  • Go to the https://console.cloud.google.com/
  • Find in menu: APIs & Services -> Enabled APIs & Services
  • Disable 3 services: "Cloud Firestore API”, “Firebase Rules API”, "Cloud Storage for Firebase API”
  • Find in menu: Firestore -> It will automatically enable "Cloud Firestore API” & “Firebase Rules API” services and will create Firestore Database.
  • Enable "Cloud Storage for Firebase API”.
  • 最重要的是要从谷歌云控制台创建一个Firestore数据库。

    Chris Webb
    Chris Webb
    发布于 2022-01-04
    0 人赞同

    再补充一个原因--AppCheck。我在一个新项目上启用了它(创建于2022年5月),但没有完成整合步骤,导致 "权限缺失或不足 "的错误。

    要解决这个问题,首先要完成Firebase中AppCheck部分下所列的AppCheck设置步骤。我在我的网络应用中使用了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控制台来完成设置,之后你可以评论/删除这一行。

    This fixed my issue.

    Further info:

  • https://firebase.google.com/docs/app-check/web/recaptcha-provider
  • https://firebase.google.com/docs/app-check/web/debug-provider?authuser=0&hl=en
  • Elzazo Zazzaz
    Elzazo Zazzaz
    发布于 2022-01-04
    0 人赞同

    对我来说,问题是AppCheck在我的Firestore控制台也被激活了。 因此,我不得不按照应用检查Flutter指南中所说的那样做。

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

    Turned on the androidDebugProvider: true, copied the debug token from the console and pasted it in the Firestore section (AppCheck --> app --> add debug token) and it worked immediately.

    Pasindu Ranasinghe
    Pasindu Ranasinghe
    发布于 2022-01-04
    0 人赞同

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

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

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