【问题标题】:Missing or insufficient permissions when writing to Firestore using field in access rules使用访问规则中的字段写入 Firestore 时缺少权限或权限不足
【发布时间】:2018-03-20 00:52:21
【问题描述】:

我在尝试写入 Firestore 时遇到错误。

我正在尝试将包含用户 uid 的字段用于我的安全规则。

service cloud.firestore {
  match /databases/{database}/documents {

    match /messages/{document=**} {
      allow read: if resource.data.user_uid == request.auth.uid;
      allow write: if resource.data.user_uid == request.auth.uid;
    }
  }
}

如果我的 Firestore 数据库中有数据,则读取规则可以正常工作 - 但是当我尝试写入时,我得到:Error: Missing or insufficient permissions. 这个写规则有什么问题吗?

附:如果我将规则更改为此,我可以写入我的数据库 - 但这对于我的目的来说不够安全:

 match /messages/{document=**} {
      allow read: if resource.data.user_uid == request.auth.uid;
      allow write: if request.auth != null;
    }

【问题讨论】:

    标签: firebase firebase-security google-cloud-firestore


    【解决方案1】:

    resource.data 指的是已存储的数据,因此您的规则允许用户仅更新已包含其用户 ID 的数据。

    您可能要检查的是request.resource.data,它是传入的新数据。

    这里有一个关于这些字段和其他安全规则的相当广泛的文档:https://firebase.google.com/docs/firestore/security/rules-conditions

    【讨论】:

    • 感谢工作。 Firebase 文档需要更新,他们只给出了读取的例子,他们也应该给出写入的例子......
    • @LeoFarmer 这里有一个关于不同安全规则的相当广泛的文档:firebase.google.com/docs/firestore/security/secure-data
    • 这不会允许其他用户覆盖您的数据,只要他们尝试使用他们的 uid 更新它吗?如果不存在并请求 uid 匹配,也许进行粒度创建,仅当现有数据 uid 匹配时才删除,仅当请求和现有 uid 匹配时才更新?
    • 您好,非常感谢!我想知道您是否能够对我的事情有所了解,请stackoverflow.com/questions/50929366/…?非常感谢!
    • 修复了当前文档中最匹配页面的链接。
    【解决方案2】:

    这个问题和接受的答案对我非常有用。我最终使用了一组略有不同的规则,我将在这里分享,以防其他人发现它们有用。

    与 OP 一样,我将用户 ID (uid) 与我的资源一起存储。但是,当我想创建一个新资源时,还没有uid。使用example in the documentation,我最终得到了如下所示的安全规则:

    service cloud.firestore {
      match /databases/{database}/documents {
        match /messages/{document=**} {
          allow read, update, delete: if request.auth.uid == resource.data.uid;
          allow create: if request.auth.uid != null;
        }
      }
    }
    

    【讨论】:

      【解决方案3】:

      您可以使您的数据库仅用于读取而不用于写入:

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

      【讨论】:

        【解决方案4】:

        对我来说,这组代码适用于 Firestore 安全

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2018-04-25
          • 1970-01-01
          • 1970-01-01
          • 2018-08-14
          • 2019-02-26
          • 2018-12-06
          • 1970-01-01
          相关资源
          最近更新 更多