【问题标题】:Firebase security rules for Chats / Messages聊天/消息的 Firebase 安全规则
【发布时间】:2020-09-10 19:45:51
【问题描述】:

尝试实施一些 Firebase 规则,在大多数情况下,auth != null 目前还不错,但接下来我们会谈到聊天和消息等内容,我希望这些内容拥有更严格的安全规则。

我保存聊天记录的方式如下:Chats > MessageId (created by Firebase) > Receiver, Sender, Timestamp, etc. 不知道如何编写规则,特别是对于 Firebase 会在创建新聊天时创建的唯一 MessageId

我应该以不同的方式构建我的数据,或者这是我将聊天保存到数据库的方式可接受的方案吗?

到目前为止我尝试过的是这样的:

"Chats": {
         "$uid1": {
           "$uid2": {
             ".read": "auth.uid == $uid2",
               ".write": "auth.uid == $uid2",
           },
             ".read": "auth.uid == $uid1",
               ".write": "auth.uid == $uid1"
         }
       }

,但它不起作用。由于某种原因,主屏幕无法加载...

有人可以分享如何为我在这里进行的此类聊天实施良好的安全规则吗?

【问题讨论】:

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


    【解决方案1】:

    MessageId 由 firebase 创建。 Auth-id 是您的用户 ID。你无法将两者进行比较。你可以试试这个:

    {
      "rules": {
        "Chats": {
          "$message_id": {
            // any logged in user can get a list of messages
           ".read": "auth !== null",
    
            // sender can be write
            ".write": "newData.child('sender').val() === auth.uid"
          }
        },
        "Chatslist": {
          "$user_id": {
            ".read": "auth.uid === $user_id",
            ".validate": "root.child('users/'+$user_id).exists()",  
            "$receiver_id": {
               // user must already exist to add a new receiver
              ".write": "root.child('users/'+$receiver_id).exists()"
            }
          }
        }
      }
    }
    

    我不确定,但您可以阅读docs。有一个类似的例子

    【讨论】:

    • 有什么问题?
    • 我上传了 JSON 结构的截图。我认为问题可能出在 Chatlist 节点上,也许我也必须为其编写不同的 Firebase 规则,但是当我将 Chats 的规则更改为上述规则时,主屏幕上没有加载任何内容。
    • 是的,您必须为所有这些都编写规则。我编辑了我的答案。你能试试这个吗?
    • 嘿,Kasim,刚试了一下,没用。当我将规则更改为上述规则时,主屏幕保持空白。我将尝试查看是否可以使用文档解决此问题。我认为问题可能是 $messageId,但我不确定...
    猜你喜欢
    • 2021-01-05
    • 2014-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-27
    • 1970-01-01
    相关资源
    最近更新 更多