【问题标题】:Firestore Security Rules: How to enforce the number of fields CREATED in a Firestore document thru security rules? [duplicate]Firestore 安全规则:如何通过安全规则强制在 Firestore 文档中创建的字段数? [复制]
【发布时间】:2019-08-26 18:29:32
【问题描述】:

我无法使用 Firestore 安全规则限制创建的文档中的字段数。 https://firebase.google.com/docs/firestore/security/rules-structure

我的用户文档中有 7 个字段。我想将任何文档 CREATE 尝试限制为我期望的字段数。我已将数字设置为 100,这显然不是我发送给故意造成失败的数字。我预计 100 会失败,但事实并非如此。

match /users/{uid} {
  // Applies to writes to nonexistent documents
  allow create: if request.resource.data.size() == 100;
}

我还尝试了以下方法,将 size 属性直接放在资源对象上,但没有成功。

允许创建:如果 request.resource.size() == 100;

这是尝试创建操作的代码;

const DEFAULT_systemRole = 'User';
  const DEFAULT_disabled = false; 
  // creates up a static sentinel value to be set on the Firestore server
  var serverTimestamp = admin.firestore.FieldValue.serverTimestamp()
  admin.firestore().collection('users').doc(req.body.uid).set({

    // sent from client
    usernameSlug: req.body.usernameSlug,
    username: req.body.username,
    email: req.body.email,

    // set only here on server
    systemRole: DEFAULT_systemRole,
    disabled: DEFAULT_disabled,
    dateModified: serverTimestamp,
    dateCreated: serverTimestamp,

  }).then(function() {
    console.log("Successfully created FireStore user");
  }).catch(function(error) {
    console.log("Error creating user:", error);
    throw(error)
  }) 

【问题讨论】:

  • 请将问题编辑为如何编写文档的代码。不确定您的规则是否真的适用于您正在执行的写入,因为我们不知道该写入的真正含义。

标签: node.js google-cloud-firestore firebase-security


【解决方案1】:

我刚刚在模拟器中快速测试了这个,它似乎对我有用:

所以上述安全规则需要 2 个字段。

当我编写一个只有一个字段的新文档时(在屏幕截图中),写入失败。

当我将规则更改为只需要一个字段时,同样的写入会成功。

【讨论】:

  • 谢谢弗兰克,我刚刚意识到我的问题是我使用的是不支持安全规则的 Firebase Admin sdk。
【解决方案2】:

我碰巧使用的 Firebase Admin sdk 似乎在设计上不支持 Firebase 安全规则。相反,Firebase Admin sdk 绕过所有安全规则。因此,看起来我会将所有调用移至 Firebase Admin sdk,并使用以下规则简单地锁定 Firestore 数据库,以防止任何客户端黑客攻击的可能性。

  match /users/{uid} {

    allow read, write: if false;

  }

下面的帖子也发现了同样的情况; How to get Firestore rules working with service accounts

【讨论】:

    猜你喜欢
    • 2020-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-21
    • 2020-02-13
    • 2018-10-19
    • 2019-07-05
    • 2020-08-21
    相关资源
    最近更新 更多