【问题标题】:Firebase Realtime Database Security Rules protect user datasFirebase 实时数据库安全规则保护用户数据
【发布时间】:2020-01-15 02:52:50
【问题描述】:

我正在开发一个我想在 firebase 实时数据库上运行的项目。我用这种格式创建了一个数据库设置:

   {
  "Horses" : {
    "description" : "",
    "id" : "",
    "name" : "",
    "uid" : "testx"
  },
  "images" : {
    "full_path" : "",
    "horse_id" : "",
    "id" : "",
    "thumbnail_path" : "",
    "uid" : ""
  },
  "videos" : {
    "full_path" : "",
    "horse_id" : "",
    "id" : "",
    "thumbnail_path" : "",
    "type" : "",
    "uid" : ""
  }
}

我的安全规则如下所示:

    {

  "rules": {
    "Horses":{
      ".read": true,
        ".write": false,

        "$uid":{
            ".read": true,
                ".write": "$uid == auth.uid"
        }

    },
    "videos":{
      ".read": true,
        ".write": false,

        "$uid":{
            ".read": true,
                ".write": "$uid == auth.uid"
        }

    },
    "images":{
      ".read": true,

        "$uid":{
            ".read": true,
                ".write": "$uid == auth.uid"
        }

    },
  }

}

我正在尝试归档每个人都可以阅读“马”、“图像”和“视频”中的详细信息,但只有经过身份验证的用户才能将条目添加到“马”、“图像”和“视频”中,如果它们属于他们自己(由 firebase auth 提供的用户 ID 检查)。

我的第一个问题是:我是否应该将“图像”和“视频”作为“马”的子对象包含在内?如果我可以一次为 Horse 编写一个读写规则,它会级联到其他规则,那就更好了。

我的第二个问题是:即使身份验证设置为与我写入的数据相同的 uid,我也无法将集合写入马或图像。例如,我似乎必须将我的请求发送到horses/[UID-HERE]。我如何编写将我描述的行为归档的规则?

感谢您的帮助!

【问题讨论】:

  • 在你的例子中你没有错过每个节点下的一个键吗?

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


【解决方案1】:

首先:在 Horses 中嵌套视频和图像取决于您的使用情况。当它们相关时,您可以嵌套这些值,例如:

社交网站上的帖子将具有以下结构:

siteData:{
postid:{
   postTitle: value,
   videos : {
    "full_path" : "",
    "horse_id" : "",
    "id" : "",
    "thumbnail_path" : "",
    "type" : "",
    "uid" : ""
  },
    "images" : {
    "full_path" : "",
    "horse_id" : "",
    "id" : "",
    "thumbnail_path" : "",
    "uid" : ""
  }
}
}

我们在这里嵌套了它们,因为它们与帖子直接相关。

另一种情况是,当我们只想存储网站上的所有图像和视频时,结构将是:

  siteData:{
  "images" : {
    "full_path" : "",
    "horse_id" : "",
    "id" : "",
    "thumbnail_path" : "",
    "uid" : ""
  },
  "videos" : {
    "full_path" : "",
    "horse_id" : "",
    "id" : "",
    "thumbnail_path" : "",
    "uid" : ""
  },
  posts:{
  somePostId:{}
  }
  }

您在这里看到视频和图片没有嵌套在帖子中。

第二:

检查用户 ID:

"images":{
  ".read": true,
  "$uid": {
      ".read": true,
      ".write": "auth.uid == $uid"
       }
    }

基本上,这里的data 将引用该规则处理的引用处的数据。

你可能想看看这个:https://gist.github.com/codediodeio/6dbce1305b9556c2136492522e2100f6

【讨论】:

  • 但在这种情况下,用户可以从数据库中读取所有 uid 并在 webapp 中使用它进行授权吗?感谢您的帮助!
  • 我没看懂你的问题,你说的读出是什么意思。
  • 我更新了上面的图片。即使数据包含与身份验证令牌相同的 uid,我仍然无法写入 /Horses。请忘记我的第一条评论,我不明白“auth.uid”变量背后的想法。这对我的需要应该是安全的^^
  • 尝试使用 $data.uid
  • 嘿,这看起来不错。但它似乎不会阻止用户可以将具有自己 uid 的图像添加到其他 uid 的马。如果我将其拆分为 3 个“表”,我必须确保 horse_id 已针对用户进行验证.. 嗯
猜你喜欢
  • 2019-01-07
  • 2020-08-08
  • 1970-01-01
  • 2020-12-28
  • 2021-10-26
  • 2021-02-13
  • 2018-08-27
  • 2021-02-11
相关资源
最近更新 更多