保护Firebase数据

时间:2016-10-05 02:11:00

标签: firebase firebase-security

我第一次尝试设置Firebase规则。我想要做的是限制对登录用户的访问,以便他们只能访问他们的数据。他们自己的数据位于usersusercontacts。任何人都可以写contactmessages路线,没有人可以阅读。

这套规则是否符合我的预期?我在模拟器中尝试了它并得到simulated write denied错误。我可能在模拟器上做错了。

{
  "rules": {
    "users": {
      "$user_id": {
        // grants read/write access to the owner of this user account
        // whose uid must exactly match the key ($user_id)
        ".write": "$user_id === auth.uid",
        ".read": "$user_id === auth.uid"
      }
    },
    "usercontacts":{
        "$user_id": {
              ".write": "$user_id === auth.uid",
              ".read": "$user_id === auth.uid"
        }
    },
    "contactmessages": {
        ".read" : false,
        ".write" : "$user_id === auth.uid"
    }
  }
}

2 个答案:

答案 0 :(得分:0)

试试这个

{
  "rules": {
    "users": {
        "$userId":{
             ".read": "(auth != null) && ($userId === auth.uid)",
             ".write": "(auth != null) && ($userId === auth.uid)"
        }
     },
     "usercontacts": {
        "$userId": {
              ".read": "(auth != null) && ($userId === auth.uid)",
              ".write": "(auth != null) && ($userId === auth.uid)"
        }
      },
      "contactmessages": {
        "$userId": {
              ".read": "(auth != null) && ($userId === auth.uid)",
              ".write": "(auth != null) && ($userId === auth.uid)"
        }
      }
  }
}

答案 1 :(得分:0)

这里的问题在于你的上一个写规则:

"contactmessages": {
    ".read" : false,
    ".write" : "$user_id === auth.uid"
}

您正在使用$ user_id,但没有任何$ user_id可供引用。相反,如果您希望任何人能够在此处书写,您应该使用此规则:

".write" : true

如果您希望每个经过身份验证的用户都能够编写此规则:

".write" : "auth != null"