【问题标题】:Firebase 3.0 Security Rules - Don't allow to push anonymous childrenFirebase 3.0 安全规则 - 不允许推送匿名孩子
【发布时间】:2016-09-28 17:27:47
【问题描述】:

我正在构建一个允许用户标记他们的工作时间的应用程序。在我的应用程序中有两种类型的用户。其中一个是只有读取权限的“员工”,另一个是具有读写权限的“管理员”。员工可以阅读自己的工作时间,管理员可以创建新用户或为每个用户/员工添加工作时间。

管理员填写表格并推送数据。在 firebase 上,我检查了用户是否经过身份验证,并对用户对象的每个属性进行了验证。但我在问自己,如果有人复制我的 firebase url(在源代码中可见)并尝试将一些匿名对象或属性推送到我的数据库中怎么办?

例如,我有一个需要此字段的注册表单:

{ 
   "users": {
      "-KInd4V0V9k5n6yhAETd": {
         "uid": "-KInd4V0V9k5n6yhAETd",
         "username": "Haris",
         "password": "HelloWolrd123",
         "age":      "21"
         }
    }
}

在 firebas 方面,我已经使用 newData 方法检查了子元素是否从表单传递:

".validate": "newData.hasChildren(['uid','username','password,'age'])"

我已经对每个属性进行了验证,以检查数据是否有效,例如 username.isString() 等。

如果管理员使用这样的开发者工具将用户对象推送到我的数据库中会怎样(添加了电子邮件属性)

 {
    "-KInd4V0VEEEEEEEE": {
         "uid": "-KInd4V0VEEEEEEEE",
         "username": "Haris",
         "password": "HelloWolrd123",
         "age":      "21",

         // anonymous Object pushed from n admin developer-console
          "email": "anonymous@object.com"
         }
}

这会起作用,因为所有必填字段都是有效的,并且在 firebase 上通过了验证。但是我如何否认管理员不能添加和传递'email'属性到我的firebase数据库?因为我在数据库上的用户对象结构没有电子邮件属性。我不想让用户可以将他自己的匿名对象/数据推送到我的数据库。我需要验证每个属性还是有一种方法可以验证对象本身?像 newData('users').isValid()?如果一个属性是附加的,那么 isValid 会返回 false,因为该对象与数据库结构中的对象不同?

【问题讨论】:

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


    【解决方案1】:

    我不完全确定,但认为您正在寻找一个拒绝所有其他孩子的规则。如果这确实是您正在寻找的,那么:

    {
      "rules": {
        "users": {
          "$uid": {
            // Valid users have these properties
            ".validate": "newData.hasChildren(['uid','username','password,'age'])",
            // The uid property must be a string and refer to an existing noder under /users
            "uid": {
              ".validate": "newData.isString() && root.child('users').child(newData.val()).exists()"
            },
            // the user name must be a string
            "username: {
              ".validate": "newData.isString()"
            },
            "password: {
              // I really hope you're not storing a password
            },
            "age: {
              // TODO: you're storing age as a string now, might want to fix that
              ".validate": "newData.isNumber()"
            },
            // All other properties are rejected
            "$other": {
              ".validate": false
            }
          }
        }
      }
    }
    

    【讨论】:

    • 谢谢弗兰克!这正是我想要的。
    猜你喜欢
    • 2023-04-10
    • 1970-01-01
    • 1970-01-01
    • 2020-07-11
    • 2021-07-14
    • 2016-02-26
    • 1970-01-01
    • 2017-06-13
    • 1970-01-01
    相关资源
    最近更新 更多