如何仅允许使用 Firebase 进行身份验证的用户读/写对象? [英] How to allow read/write objects only to authenticated user with Firebase?
问题描述
我正在尝试对在 Firebase 中存储笔记对象进行简单的测试,并使用用户安全规则确保笔记只能读写给作者.
I am trying to make a simple test of storing notes objects in Firebase, with user security rules that ensure the notes can be read and write only to the author.
Firebase 中存储的数据如下所示:
Here is what the data stored in firebase looks like:
my_firebase_db
- notes
- K835Tw_H28XXb-Sj4b
- text: "note 1 from author 1",
- user_id: "11b09925-534b-4955-ac55-3e234809432f"
- K835Tw_H28XXb-Sj4b
- text: "note 1 from author 2",
- user_id: "11b09925-534b-4955-ac55-4d223893382c"
- K835Tw_H28XXb-Sj4b
- text: "note 2 from author 2",
- user_id: "11b09925-534b-4955-ac55-4d223893382c"
使用自定义令牌验证用户身份的 Angular 代码 (AngularFire)、加载注释和添加注释的方法:
Angular code (AngularFire) that authenticates the user with a custom token, load notes and method to add a note:
var ref = new Firebase("https://xxx.firebaseio.com");
// Authenticate users with a custom authentication token
$firebaseAuth(ref).$authWithCustomToken(data.token).then(function(authData) {
console.log("Logged in as:", authData.uid);
$scope.user_id = authData.uid;
}).catch(function(error) {
console.error("Authentication failed:", error);
});
// Load notes
$scope.notes = $firebaseArray(ref.child('notes'));
$scope.addNote = function() {
note = {
user_id: $scope.user_id,
text: $scope.newNote.text
};
$scope.notes.$add(note);
};
安全&Firebase 中的规则设置:
Security & rules setup in Firebase:
{
"rules": {
"notes": {
".read": "auth != null && data.child('user_id').val() === auth.uid",
".write": "auth != null && newData.child('user_id').val() === auth.uid"
}
}
}
有了这些规则,阅读 &不允许写.
With these rules, read & write is not allowed.
如果我将规则更改为此,请阅读 &允许写(但作者可以阅读每个人的笔记):
If I change the rules to this, then read & write are allowed (but authors can read everybody's notes):
{
"rules": {
"notes": {
".read": "auth != null",
".write": "auth != null"
}
}
}
如何在 firebase 中编写安全规则,以允许经过身份验证的用户读取 &自己写笔记?
How can I write a security rule in firebase that will allow the authenticated user to read & write their own notes?
推荐答案
原来答案在这里:"规则不是过滤器".
这篇关于如何仅允许使用 Firebase 进行身份验证的用户读/写对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!