【问题标题】:Firebase DatabaseError: Permission deniedFirebase 数据库错误:权限被拒绝
【发布时间】:2016-11-11 06:51:35
【问题描述】:

我想在 firebase 的 Items 节点上保存一些数据。当我的规则是时,我能够保存

"Items":{
   ".write": "auth != null",
   ".read": "auth != null"
}

但我希望用户编写/更新他们的自己的项目并且我不想使用$变量,因为它会在我的路径上添加一些数据。那是

下面的方法将在我的路径上添加一些数据而不是/Items,它将是/key/Items

{


"rules": {
    "Items": {
      "$user_id": {
        ".read": "auth != null",
        ".write": "$user_id === auth.uid"
      }
    }
  }
}

因此,我看到的最好的方法就是这样写我的规则

"Items":{
       ".read": "auth != null",
        ".write": "(data.exists() && data.child('userId').val() === auth.uid) || (!data.exists() && newData.child('userId').val() === auth.uid)"

}

}

当我在模拟器上运行以下代码时,一切正常

 {
"userId":"xxxxxxxxxxxxxxxxx"
}

但是当我尝试从手机上传数据时,出现错误

setValue at /Items/-KWH6tgdLPGTdascf-w3 failed: DatabaseError: Permission denied

我哪里错了?

【问题讨论】:

    标签: android firebase firebase-realtime-database firebase-authentication


    【解决方案1】:

    更简单的方法是在允许用户更新并将对象推送到 Firebase 之前检查登录用户的 id 是否与 userId 变量存储的 id 相同。

    FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
    Item item;
    if (user != null) {
       //logged in
       String uid = user.getUid();
       if(uid.equals(item.getUserId()){
        //allow the user to update item.
       }
    } else {
      //not logged in
    }
    

    【讨论】:

      【解决方案2】:

      设置数据库读写规则为true

      "Items":{
         ".write": "true",
         ".read": "true"
      }
      

      【讨论】:

      • 但这会让每个人都编辑数据。我只希望数据所有者这样做
      • 这种情况下你只需要使用$,检查this和this
      • 添加“$”将迫使我在我的路径中包含一些额外的数据。那就是我的数据库引用应该指向/items/key/。我不想包含任何键
      【解决方案3】:

      根据实时数据库的最新版本,请执行以下操作: https://firebase.google.com/docs/firestore/security/get-started?authuser=0

      将此添加到数据库中的选项卡规则中:

          // Allow read/write access to all users under any conditions
      // Warning: **NEVER** use this rule set in production; it allows
      // anyone to overwrite your entire database.
      service cloud.firestore {
        match /databases/{database}/documents {
          match /{document=**} {
            allow read, write: if true;
          }
        }
      }
      

      【讨论】:

        猜你喜欢
        • 2017-04-17
        • 2016-09-25
        • 2019-11-15
        • 2018-03-27
        • 1970-01-01
        • 2020-10-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多