Firebase 安全规则不起作用

The Firebase security rules not works

我对 Firebase 规则有疑问。基本上我有一个名为 'users' 的根文件夹,其中包含许多再次包含数据的用户 ID,就像这样:

users {
    userid1 {
        info_user {
            a: {
                a1: whatever
                a2: whatever       
                a3: {
                    a3.1: whatever
                    a3.2: whatever
                    a3.3: whatever
                    a3.n: whatever
                }
            }
            n: {} ...
        }
    },
    userid2 {}, ...n
}

如果没有安全规则,运行以下代码时一切正常,例如:

{rules {".read"  : true, ".write" : true}}

function getUserInfo () {
    var dbRef = firebase.database();
    var myArray = [];
    dbRef.ref('users').on('child_added', function(snapshot) {
        snapshot.forEach(function(childSnapshot) {
            myArray = (childSnapshot.val().a3);
            // do something
        });
    });
}

我的挑战 是在不改变数据库结构的情况下改变安全规则。

所以,我试着做这样的事情:

{
    "rules" : {
        ".read"  : false,
        ".write" : false,
        "users": {
            "$userid": {
                "info_user": {
                    "a":{
                        ".read": "auth != null",
                        ".write": "(root.child('r').child('w').hasChild(auth.uid))",
                        "a1":{".validate": "newData.isString()"},
                        "a2":{".validate": "newData.isString()"},
                        "a3":{".validate": "newData.isString()"}
                    },
                    "n": {
                        ".read": "auth != null",
                        ".write": "$user_id === auth.uid"
                    }
                }
            }
        }
    }
}

预期结果是在用户通过身份验证时读取节点 a3

如何操作?

首次附加侦听器时,会强制执行 Firebase 数据库读取权限。因此,当您将侦听器附加到 dbRef.ref('users') 时,您必须具有对 /users 的读取权限。在您的安全规则中,情况并非如此。

要使规则生效,请将读取权限上移到`users:

{
  "rules" : {
    "users": {
      ".read"  : "auth != null",
      ...

请注意权限向下级联。因此,一旦您授予用户对 /users 的读取权限,他们就可以访问 /users 下的所有数据。您不能为那里的特定节点取消此权限。

这导致了保护 Firebase 数据库的陷阱之一:不能使用规则来过滤数据。有关更多信息,请参阅 Firebase documentation on "rules are not filters", this answer about it and many more of the questions from developers struggling with the concept.