【问题标题】:Firebase rules not allowing user to write data in androidFirebase 规则不允许用户在 android 中写入数据
【发布时间】:2016-08-09 13:00:36
【问题描述】:

这是数据库结构。

这是数据库规则:

{
  "rules": {
    ".read": true,
    "shops-product-list": {
        "$uid": {

        // grants write access to the owner of this user account whose uid must exactly match the key ($uid)
        ".write": "auth !== null && auth.uid === $uid",
        }
    }
  }
}

shops-products-list 的键是登录用户的 uid(忽略第一个键,即 -1)

登录用户尝试使用此逻辑写入新数据。

private void addShopVariant(String pid, String vid, String mrp, String sellPrice) {
    // Create new post at /user-posts/$userid/$postid and at
    // /posts/$postid simultaneously

    final String uid = getUid();
    String key = pid + "_" + vid;
    //String key = databaseReference.child("shops-product-list").child(uid).push().getKey();

    ShopProductVariant shopProductVariant = new ShopProductVariant(pid, vid, mrp, sellPrice);
    Map<String, Object> shopProductVariantValues = shopProductVariant.toMap();
    Map<String, Object> childUpdates = new HashMap<>();
    childUpdates.put("/shops-product-list/" + uid + "/"+ key, shopProductVariantValues);
    //childUpdates.put("/user-posts/" + userId + "/" + key, postValues);

    databaseReference.updateChildren(childUpdates);
}

如果我设置规则,功能就可以正常工作。

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

但我希望只有登录用户才能写入,也只有他们自己的数据。

Firebase 规则有什么问题?

【问题讨论】:

  • 乍一看,这些规则似乎应该有效。您可以进一步减少代码以仅使用常量值吗?例如:getUid() 返回什么?那真的是登录用户吗?另请注意,updateChildren() 带有一个完成侦听器,它可能会告诉您有关操作失败原因的更多信息。

标签: firebase firebase-realtime-database firebase-security


【解决方案1】:

我认为你的规则是错误的设置:

应该是这样的:

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

注意语法是 != 而不是 !==

编辑: 您可以这样做,而不是在服务器上验证它:

scoresRef.child("the user id").setValue("your value", withCompletionBlock: { (error:NSError?, snapshot:FIRDatabaseReference) in


})

这样你就不必在规则中这样做了

【讨论】:

  • 我认为它只有 !==。请查看此官方文档链接。 firebase.com/docs/security/guide/user-security.html
  • 我实际上是在使用这种语法来配置我的规则。
  • 我也尝试了 !=,但仍然权限被拒绝错误
  • 如果你尝试删除这部分会得到什么 "&& auth.uid === $uid"
  • 在 Firebase 中,安全规则 ===== 被视为相同,!=!== 也是如此。
猜你喜欢
  • 2018-01-05
  • 1970-01-01
  • 2020-06-09
  • 1970-01-01
  • 2020-08-19
  • 1970-01-01
  • 2020-03-22
  • 2021-06-24
  • 2018-08-12
相关资源
最近更新 更多