23

我在文档中找不到它,但是有没有办法定义一组用户并使用该组来授予对不同位置的访问权限,而不是授予对单个用户的访问权限?

问候, LT

4

1 回答 1

37

Firebase 中没有明确支持“组”,因为您可以很容易地自己表示它们。根据您的情况,这里有两种选择。

在 firebase 中存储组信息。

以下数据可用于表示 2 个组(“alpha”和“beta”)和 3 条受保护数据(“thing1”、“thing2”和“thing3”)

{
  "groups": {
    "alpha": {
      "joe": true,
      "sally": true
    },
    "beta": {
      "joe": true,
      "fred": true
    }
  },
  "data": {
    "thing1": {
      "group": "alpha"
      /* data accessible only by the "alpha" group */
    },
    "thing2": {
      "group": "beta"
      /* data accessible only by the "beta" group */
    },
    "thing3": {
      "group": "alpha"
      /* more data accessible by the "alpha" group */
    }
  }
}

然后我们可以使用以下规则来强制执行安全性:

{
  "rules": {
    "data": {
      "$thing": {
        ".read":  "root.child('groups').child(data.child('group').val()).hasChild(auth.id)",
        ".write": "root.child('groups').child(data.child('group').val()).hasChild(auth.id)"
      }
    }
  }
}

因此,如果我使用 { id: 'sally' } 作为我的身份验证对象进行了身份验证,我将可以访问 thing1 和 thing3,但不能访问 thing2。

将组信息存储在身份验证令牌中。

如果您正在生成自己的身份验证令牌,并且您知道用户在进行身份验证时所在的组,则可以将组列表存储在您生成的身份验证令牌中。例如,当您为用户“fred”生成身份验证令牌时,包括“{ id: 'fred', groups: { alpha: true, beta: true } }”

然后您可以通过以下方式强制执行组成员身份:

{
  "rules": {
    "data": {
      "$thing": {
        ".read": "auth[data.child('group').val()] != null",
        ".write": "auth[data.child('group').val()] != null"
      }
    }
  }
}
于 2013-01-24T00:53:30.743 回答