首页 > 解决方案 > 添加安全规则,让用户仅在 Firebase 中读取包含其 uid 的数据

问题描述

我在我的 firebase 控制台中编写了这些安全规则,以让项目和联系人只有在登录用户的 uid 与项目和联系人 uid 值匹配时才能获得读写权限。我验证了匹配的 uid,但不再可见项目或联系人。

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

注意:每个项目都包含一个具有用户 uid 的值。

我的数据库结构:

my-database:
   - Projects
      -MYGDH884934939
         uid: xxxxxxx
   - Contacts
      -MYGDH535578889
         uid: xxxxxxx

登录用户具有相同的 uid = xxxxxxx

标签: reactjsfirebasefirebase-realtime-databasefirebase-authentication

解决方案


像这样的东西?

{
  "rules": {
    "Projects": {
      "$uid": {
        ".read": "$uid === auth.uid",
        ".write": "$uid === auth.uid"
              }
      },
"Contacts": {
      "$uid": {
        ".read": "$uid === auth.uid",
        ".write": "$uid === auth.uid"
              }
      }
   }
}

推荐阅读