Firebase数据库安全规则 [英] Firebase database security rules

查看:162
本文介绍了Firebase数据库安全规则的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我正在研究一个简单的应用程序,用户可以维护一个记录列表,任何人都可以阅读,只有创建该记录的用户才能编辑或删除。

只要将其视为待办事项应用程序即可,其中经过身份验证的用户可以管理任务列表。用户可以读取任何其他任务列表,但只有创建任务的用户才能删除或编辑它。



我尝试了不同的选项,但未能提出正确的安全策略。



是否有任何示例可以遵循或者有关如何构造数据来简化安全策略的建议?

示例安全规则



我已经尝试过这样的事情 -

 rules:{
records:{
.read:true,
$ user_id:{
.write :auth.uid === $ user_id
}
}
}
}

所以任何人都可以读取记录,但只有登录user_id的用户才能够添加,编辑或删除记录。



但是,当我在模拟器中尝试写入操作时,我总是得到写入拒绝错误。我在身份验证数据中传递auth uid为user_id。

我也试过了

$ p
rules:{
records:{
.read:true,
.write:auth .uid === data.child('user_id')。val()
}
}
}


解决方案

我在文档中找到了这个。节点用户具有以auth.uid作为关键字存储的子节点。因此,在写入该条目之前,基本上比较用户uid和密钥:

  {
rules:{
users:{
$ user_id:{
//授予对此用户帐户所有者的写入权限
//其uid必须与该密钥完全匹配($ user_id)
.write:$ user_id === auth.uid,
.read:true
}
}
}
}

https://www.firebase.com/docs/security/guide/user-security.html


I am really struggling with firebase database security rules.

I am working on a simple app, where users can maintain a list of records, which anyone can read but only the user who created the record can edit or delete.

Just consider it like a todo app, where authenticated users can manage list of tasks. Users can read each others task list but only the user who created the task can delete or edit it.

I have tried different options but failed to come up with correct security policy.

Is there any example I can follow or any recommendation on how to structure the data to simplify security policy ?

Sample security rule

I have tried something like this -

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

So that anyone can read records but only logged in user with matching user_id should be able to add, edit or delete a record.

However, when I try a write action in simulator, I always get write denied error. I am passing the auth uid as "user_id" in request body/data.

I have also tried

{
 "rules": {
 "records" : {
   ".read" : true,
    ".write": "auth.uid === data.child('user_id').val()"
     }
   }
}

解决方案

I found this in the documentation. The node users has childs stored with auth.uid as a key. So you basicly compare the users uid to the key before writing to that entry:

{
  "rules": {
    "users": {
      "$user_id": {
        // grants write access to the owner of this user account
        // whose uid must exactly match the key ($user_id)
        ".write": "$user_id === auth.uid",
        ".read": true
      }
    }
  }
}

https://www.firebase.com/docs/security/guide/user-security.html

这篇关于Firebase数据库安全规则的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆