Firebase 的安全规则
Security Rules with Firebase
我在一个正在开发的项目中使用了一段时间的 Firebase,但到目前为止并没有太担心安全问题。从现在开始,我想实施一些安全规则。我已经阅读了 Firebase 网站上关于该主题的快速入门教程,但我还不确定它们是如何组合在一起的。
这里是我的数据结构:
myApp
- DataList
- Contents
- randomKey_One
value: "grgrsgs;jj…data…data.."
- randomKey_Two
value: "43efdsd7gs;jj…data…data.."
- randomKey_Three
value: "8dfsvshj…data…data.."
…….
- Names
- randomKey_One
- authorID: "PeterLogID"
- name: "RecordOne_Peter"
- randomKey_Two
- authorID: "JohnLogID"
- name: "RecordStar_byJohn"
- randomKey_Three
- authorID: "PeterLogID"
- name: "RecordTwo_Peter"
…….
Contents和Names是一一对应的,通过randomKey_One、randomKey_Two、……等值建立。
创建新记录时会自动生成这些键。我将用户的登录 ID 存储在名称部分的 authorID 字段中。
我想要的是:
1) To have read access for the whole world to all the data (possibly with the exception of authorIDs).
2) To give write(and delete) access to a record, only if the authorID field matches auth.uid (i.e. the logged in user).
我已经弄清楚了第 1 部分),忘记了“authorIDs 例外”。
我该如何处理第 2 部分)?
我在这一点上所做的尝试没有奏效。
我遇到的一个问题是我不知道如何访问安全规则脚本中的 authorID 字段,因为我不知道其父项的名称。
对于那些有一天可能会遇到同样问题并阅读本文的人。
几个小时后,我把我想出的解决方案放在这里。由于是第一次接触Firebase Security Rules,欢迎有这方面的高手评论。
{
"rules": {
".read": true,
"DataList": {
"Names": {
"$Name": {
".write": "newData.child('authorID').val() === auth.uid || data.child('authorID').val() === auth.uid"
}
},
"Contents": {
"$Content": {
".write": "root.child('DataList/Names/'+$Content).exists() && root.child('DataList/Names/'+$Content).child('authorID').val() === auth.uid"
}
}
}
}
}
我在一个正在开发的项目中使用了一段时间的 Firebase,但到目前为止并没有太担心安全问题。从现在开始,我想实施一些安全规则。我已经阅读了 Firebase 网站上关于该主题的快速入门教程,但我还不确定它们是如何组合在一起的。
这里是我的数据结构:
myApp
- DataList
- Contents
- randomKey_One
value: "grgrsgs;jj…data…data.."
- randomKey_Two
value: "43efdsd7gs;jj…data…data.."
- randomKey_Three
value: "8dfsvshj…data…data.."
…….
- Names
- randomKey_One
- authorID: "PeterLogID"
- name: "RecordOne_Peter"
- randomKey_Two
- authorID: "JohnLogID"
- name: "RecordStar_byJohn"
- randomKey_Three
- authorID: "PeterLogID"
- name: "RecordTwo_Peter"
…….
Contents和Names是一一对应的,通过randomKey_One、randomKey_Two、……等值建立。 创建新记录时会自动生成这些键。我将用户的登录 ID 存储在名称部分的 authorID 字段中。
我想要的是:
1) To have read access for the whole world to all the data (possibly with the exception of authorIDs).
2) To give write(and delete) access to a record, only if the authorID field matches auth.uid (i.e. the logged in user).
我已经弄清楚了第 1 部分),忘记了“authorIDs 例外”。 我该如何处理第 2 部分)? 我在这一点上所做的尝试没有奏效。 我遇到的一个问题是我不知道如何访问安全规则脚本中的 authorID 字段,因为我不知道其父项的名称。
对于那些有一天可能会遇到同样问题并阅读本文的人。 几个小时后,我把我想出的解决方案放在这里。由于是第一次接触Firebase Security Rules,欢迎有这方面的高手评论。
{
"rules": {
".read": true,
"DataList": {
"Names": {
"$Name": {
".write": "newData.child('authorID').val() === auth.uid || data.child('authorID').val() === auth.uid"
}
},
"Contents": {
"$Content": {
".write": "root.child('DataList/Names/'+$Content).exists() && root.child('DataList/Names/'+$Content).child('authorID').val() === auth.uid"
}
}
}
}
}