Firebase规则不适用于服务器请求,但适用于模拟器

时间:2016-07-16 10:43:56

标签: javascript firebase firebase-realtime-database firebase-security

{
    "rules": {
        "verifications": {
             // Can only request verification code if it's been one minute than previous request.
            "$phoneNumber": {
                ".validate": "!data.exists() || (newData.child('timestamp').val() > data.child('timestamp').val() + 60000)"
            }
        },
        ".read": true,
        ".write": true
    }
}

此规则适用于Firebase Simulator,如果时间戳不晚于1分钟,则写入过程被拒绝。但是当我尝试从服务器写入时,它通过了规则并且允许写入过程。

代码:

var data = {
    timestamp: 1468664575179
};

var phoneNumber = '+14253452';

firebase.database().ref(`verifications/${phoneNumber}`).set(data, function(err) {
    console.log(err);
});

我想知道为什么写入过程在Firebase Simulator上被拒绝,但是当请求来自服务器时允许。

这没有给出理由: Firebase Security Rules work in simulator, but not in code

1 个答案:

答案 0 :(得分:0)

这取决于您初始化连接的方式。

如果您的服务器在不受限制的服务帐户下运行,它将以管理权限运行并绕过安全规则。

// Initialize the app with a service account, granting admin privileges
firebase.initializeApp({
  databaseURL: "https://databaseName.firebaseio.com",
  serviceAccount: "path/to/serviceAccountCredentials.json"
});

请参阅authentication section of the Firebase server docs

文档的相同部分通过在初始化时向服务器进程提供uid来解释如何覆盖此行为:

// Initialize the app with a custom auth variable, limiting the server's access
firebase.initializeApp({
  databaseURL: "https://databaseName.firebaseio.com",
  serviceAccount: "path/to/serviceAccountCredentials.json",
  databaseAuthVariableOverride: {
    uid: "my-service-worker"
  }
});