如何使用Firebase安全规则创build公开/私人用户个人资料?

{ "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" } } } } } 
  • 我已经创build了这些规则,让用户的公/私人configuration文件
  • 用户 / {uid} / public ”configuration文件应该可以被任何经过身份validation的用户访问,但不能访问“ users / 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" } } } } 

我想知道这是否是防止任何用户访问用户重要信息的可靠方法! 无论如何,我可以通过使用validation来改善这一点吗? 我很乐意接受你们的build议。 我想为我的应用程序创build最好和简单的安全规则。

您可以使用当前的数据结构来确保访问私人和公共数据。

但是,您可能需要的一个用例是显示所有用户的公共信息列表。 使用当前不可能的数据结构,因为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", } } } } 

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

嗯不会更容易(重新)结构分贝,让你有一个公共和私人领域每个用户? 就像是:

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

/ UPD:这种方式应该很容易(呃)有不同的权限,因为他们不会从父母inheritance他们?