【问题标题】:Enforce user id for a field in Firebase Database using rules使用规则对 Firebase 数据库中的字段强制执行用户 ID
【发布时间】:2017-07-26 08:44:02
【问题描述】:

我希望我的用户能够使用我的应用添加posts。我需要知道每个帖子的发帖人,以便客户使用

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 键,我想引用正在传入的值。

这是我尝试过的,但它仍然可以写帖子:

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

【问题讨论】:

    标签: javascript firebase firebase-realtime-database firebase-security


    【解决方案1】:

    第一个代码 sn-p 在语法上不正确。但假设您的意思是:

    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 实际上只是一个允许这样做的通配符规则。
    • 我现在确保您对单个帖子具有写入权限,因为仅对 userId 属性执行此操作将不再允许用户编写实际帖子。

    【讨论】:

    • 第一个代码sn-p是ES6,不好意思没提。不过新规则有效,谢谢!
    猜你喜欢
    • 2017-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-29
    • 2018-08-21
    相关资源
    最近更新 更多