【问题标题】:How to set Firebase Realtime database rules to read only child node?如何将 Firebase 实时数据库规则设置为只读子节点?
【发布时间】:2019-02-19 00:02:48
【问题描述】:

我有一个名为配置文件的节点,它有一个 id 列表。 我想只允许对子节点进行读取访问,并阻止读取所有配置文件。

这是我在规则中的内容,但它允许读取所有配置文件。

{
  "rules": {
      "profiles":{
        ".read": true,
        ".write": false  
      }
  }
} 

这就是我在个人资料下的内容

{
  "1" : {
    "id" : "1",
    "name" : "test1"
  },
  "2" : {
    "id" : "1",
    "name" : "test2"
  }
}

【问题讨论】:

  • 这个 JSON 中的值是什么意思?那么"1""2"这两个键是什么,"id" : "1"是什么意思呢?如果您显示数据库中实际 JSON 的 sn-p(作为文本,请不要截图),两者可能会更明显。您可以通过单击Firebase Database console 上溢出菜单 (⠇) 中的“导出 JSON”链接来获取此信息。

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


【解决方案1】:

通常,您会将每个用户的个人资料存储在一个密钥下,该密钥具有其 Firebase 身份验证 UID 的值。所以:

{
  "profiles": {
    "uidOfUser1": {
      "id" : "1",
      "name" : "test1"
    }
    "uidOfUser2": {
      "id" : "2",
      "name" : "test2"
    }
  }
}

在这种情况下,您可以使用以下规则保护它:

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

在安全规则中,auth.uid 的值是当前登录 Firebase 身份验证的用户的 UID。无法欺骗此值,因此这是保护数据访问的好方法。上述规则允许用户在其auth.uid 与配置文件的键匹配时读取特定配置文件。所以uidOfUser1uidOfUser2

还可以查看Firebase documentation on securing user data,其中对其进行了更详细的描述。

【讨论】:

  • 所以基本上 $user_id 意味着什么孩子的名字是给它这个规则?因为我可能在其中一个根上有一个动态子键。
  • 是的,规则中的$ 变量意味着:1)该规则下的规则适用于没有文字匹配的任何节点,2)密钥在其下的规则中可用通过$ 变量名。见firebase.google.com/docs/database/security/…。请注意,到目前为止,我已经通过安全规则文档的链接回答了您的两个问题,因此我强烈建议您阅读整个部分并节省一些时间:firebase.google.com/docs/database/security
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-02-28
  • 2019-01-18
  • 1970-01-01
  • 2020-09-20
  • 2020-03-04
  • 2019-08-30
  • 1970-01-01
相关资源
最近更新 更多