如何将Firebase实时数据库规则设置为只读子节点?

问题描述 投票:0回答:1

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

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

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

这就是我在个人档案中所拥有的

{
  "1" : {
    "id" : "1",
    "name" : "test1"
  },
  "2" : {
    "id" : "1",
    "name" : "test2"
  }
}
firebase firebase-realtime-database firebase-security-rules
1个回答
0
投票

通常,您会将每个用户的个人资料存储在具有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,它会更详细地描述它。

© www.soinside.com 2019 - 2024. All rights reserved.