小编典典

如何使用Firebase安全规则创建公共/私人用户配置文件?

json

{
“rules”: {
“users”: {
“$uid”:{
//Private whatever under “uid” but Public is exposed
“.read”: “auth != null && auth.uid == $uid”,
“.write”: “auth != null && auth.uid == $uid”,

                 "public": { ".read": "auth != null" }
                 }
               }
            }
}
  • 我创建这些规则是为了让用户拥有公共/私人资料
  • 任何经过身份验证的用户都应该可以访问“ 用户 / {uid} / 公共 ”配置文件,但不能访问“ 用户/ uid ” 下的数据

这是一些存储在我的Firebase数据库中的虚假数据。

{
  "users" : {
    "YFIIAgwa2kaannrXjwvSZmoywma2" : {
      "Name:" : "Example 1",
      //This public child should be accessible by 
      //"Example 2" but cannot know the name of 
      // this user
      "public" : {
        "email" : "example1@gmail.com"
      }
    },
    "YgSfSzPzxLbyDL17r6P9id2cdvH2" : {
      "Name:" : "Example 2",
      //This public child should be accessible by 
      //"Example 1" but cannot know the name of 
      // this user
      "public" : {
        "email" : "example2@gmail.com"
      }
    }
  }
}

我想知道这是否是防止任何用户访问用户关键信息的可靠方法!无论如何,我可以通过使用validate来改善它吗?我愿意接受你们的任何建议。我想为我的应用程序创建最佳和简单的安全规则。


阅读 307

收藏
2020-07-27

共1个答案

小编典典

您绝对可以使用当前数据结构保护对私有和公共数据的访问。

但是您可能需要在某个时候使用的一个用例是显示所有用户的公共信息列表。使用当前的数据结构是不可能的,因为Firebase的安全模型无法用于过滤数据

大多数开发人员将公共数据和私有数据划分为完全独立的子树:

{
  "users" : {
    "YFIIAgwa2kaannrXjwvSZmoywma2" : {
      "Name:" : "Example 1",
    },
    "YgSfSzPzxLbyDL17r6P9id2cdvH2" : {
      "Name:" : "Example 2",
    }
  },
  "public_profiles": {
    "YFIIAgwa2kaannrXjwvSZmoywma2" : {
      "email" : "example1@gmail.com"
    },
    "YgSfSzPzxLbyDL17r6P9id2cdvH2" : {
      "email" : "example2@gmail.com"
    }
  }
}

然后,您可以使用以下方法保护访问权限:

{
  "rules": {
     "users": {
        "$uid":{ 
             ".read": "auth != null && auth.uid == $uid",
             ".write": "auth != null && auth.uid == $uid",
        }
     },
     "public_profiles": {
        ".read": "auth != null",
        "$uid":{ 
             ".write": "auth != null && auth.uid == $uid",
        }
     }
  }
}

现在,任何经过身份验证的用户都可以收听/public_profiles,这意味着您可以轻松显示这些配置文件的列表。

2020-07-27