如何允许 read/write 个对象只允许使用 Firebase 的经过身份验证的用户?

How to allow read/write objects only to authenticated user with Firebase?

我正在尝试对在 Firebase 中存储笔记对象进行简单测试,使用用户安全规则确保笔记只能由作者读取和写入。

存储在 firebase 中的数据如下所示:

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),加载注释和添加注释的方法:

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 中的安全和规则设置:

{
  "rules": {
    "notes": {
      ".read": "auth != null && data.child('user_id').val() === auth.uid",
      ".write": "auth != null && newData.child('user_id').val() === auth.uid"
    }
  }
}

根据这些规则,不允许读写。

如果我把规则改成这样,就可以读写了(但是作者可以看大家的笔记):

{
  "rules": {
    "notes": {
      ".read": "auth != null",
      ".write": "auth != null"
    }
  }
}

如何在 firebase 中编写安全规则以允许经过身份验证的用户读取和写入他们自己的笔记?

原来答案在这里:"Rules Are Not Filters"