【问题标题】:Security Rules with FirebaseFirebase 的安全规则
【发布时间】:2016-08-19 16:52:05
【问题描述】:

我在一个正在开发的项目中使用 Firebase 已经有一段时间了,但到目前为止还没有太担心安全性。从现在开始,我想实施一些安全规则。我已经阅读了 Firebase 网站上关于该主题的快速入门教程,但我还不确定它们是如何组合在一起的。

这里是我的数据结构:

myApp
- DataList
    - Contents
        - randomKey_One
            value: "grgrsgs;jj…data…data.."
        - randomKey_Two
            value: "43efdsd7gs;jj…data…data.."
        - randomKey_Three
            value: "8dfsvshj…data…data.."
        …….
    - Names
        - randomKey_One
            - authorID: "PeterLogID"
            - name: "RecordOne_Peter"
        - randomKey_Two
            - authorID: "JohnLogID"
            - name: "RecordStar_byJohn"
        - randomKey_Three
            - authorID: "PeterLogID"
            - name: "RecordTwo_Peter"
        …….

Contents和Names是一一对应的,通过randomKey_One、randomKey_Two、...等的值建立。 创建新记录时会自动生成这些键。我将用户的登录 ID 存储在 Names 部分的 authorID 字段中。

我想要的是:

1) To have read access for the whole world to all the data (possibly with the exception of authorIDs).
2) To give write(and delete) access to a record, only if the authorID field matches auth.uid (i.e. the logged in user).

我已经弄清楚了第 1 部分),忘记了“作者 ID 的例外”。 我该如何处理第 2 部分)? 我在这一点上尝试过的没有奏效。 我遇到的一个问题是我不知道如何访问安全规则脚本中的 authorID 字段,因为我没有其父项的名称。

【问题讨论】:

  • 只是一个想法。为什么不使用用户 id 而不是随机生成的 id?
  • 这在这里不起作用,因为一个用户可能有很多记录。随机生成的 id 实际上是 childByAutoId() 产生的,它是创建新记录时的关键部分。这部分很好。

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


【解决方案1】:

对于那些可能有一天遇到同样问题并阅读本文的人。 几个小时后,我把我想出的解决方案放在这里。由于这是我第一次处理 Firebase 安全规则,欢迎任何有关该主题的专家发表评论。

{
    "rules": {
      ".read": true,
      "DataList": {
        "Names": {
          "$Name": {
             ".write": "newData.child('authorID').val() === auth.uid || data.child('authorID').val() === auth.uid"
          }
        },
        "Contents": {
          "$Content": {
            ".write": "root.child('DataList/Names/'+$Content).exists() && root.child('DataList/Names/'+$Content).child('authorID').val() === auth.uid"
          }
        }
      }
    }
}

【讨论】:

    猜你喜欢
    • 2016-06-27
    • 1970-01-01
    • 2020-09-06
    • 2016-07-16
    • 1970-01-01
    • 1970-01-01
    • 2016-03-26
    • 1970-01-01
    相关资源
    最近更新 更多