使用规则为 Firebase 数据库中的字段强制执行用户 ID

Enforce user id for a field in Firebase Database using rules

我希望我的用户能够使用我的应用添加 posts。我需要知道每个 post 是谁制作的,以便客户使用

this.firebaseapp.database().ref('posts/').push({
        userId, text, timestamp:new Date()
      });

虽然从技术上讲,有人可以修改客户端并为 userId 发送任何值,所以我需要一个数据库规则来防止这种情况。

Firebase 站点上的用户数据示例提到:

{
  "rules": {
    "users": {
      "$user_id": {
        // grants write access to the owner of this user account
        // whose uid must exactly match the key ($user_id)
        ".write": "$user_id === auth.uid"
      }
    }
  }
}

我想我基本上想要 .write 限制,但由于 Posts 是一个不同的数据集,我不想使用 Post 键,我想参考传入的值。

这是我试过的方法,但它允许 posts 仍然被写入:

{
  "rules": {
    ".read": "auth != null",
    ".write": "auth != null",
    "posts": {
      "userId": {
        ".write": "newData.val() === auth.uid"
      }
    }
  }
}

第一个代码片段在语法上不正确。但我们假设您的意思是:

this.firebaseapp.database().ref('posts/').push({
    userId: userId, text: text, timestamp:new Date()
});

您想要的规则是:

{
  "rules": {
    ".read": "auth != null",
    "posts": {
      "$postid": {
        ".write": "newData.child('userId').val() === auth.uid"
      }
    }
  }
}

主要区别:

  • 我删除了顶级 ".write" 规则。权限向下级联:一旦在某个级别授予访问权限,就无法在较低级别将其取消。
  • 我加回 $postid,这是必需的,因为此规则需要应用于 /posts 下的所有子节点。 $postid 实际上只是允许这样做的通配符规则。
  • 我现在确保您对个人 post 具有写入权限,因为仅在 userId 属性 上执行此操作将不允许用户写入实际的 post 了。