我在 Firebase 上的数据只能在我的网页上下文中读取,而不能通过打开 Firebase 网址等方式读取。
对于尚未注册的用户,我使用 signInAnonymously() 为他们提供 user.uid,但他们似乎仍然没有经过身份验证。因此,规则 ".read": "auth != null"
会导致这些用户的 PERMISSION_DENIED,即使他们拥有用户对象。
这是我的 JavaScript:
$(document).ready(function () {
var config = {
apiKey: "<my api key>",
authDomain: "<my firebase>.firebaseapp.com",
databaseURL: "https://<my firebase>.firebaseio.com",
storageBucket: "<my firebase>.appspot.com"
};
firebase.initializeApp(config);
firebase.auth().onAuthStateChanged(function (user) {
if (user) {} else {
firebase.auth().signInAnonymously();
}
});
var ref = new Firebase("https://<my firebase>.firebaseio.com/offices/some_office");
ref.on("value", function (snapshot) {
var name = snapshot.child("title").val();
console.log(snapshot.val());
}, function (errorObject) {
console.log("The read failed: " + errorObject.code);
});
});
以及相应的规则:
"offices": {
"$office_id": {
".read": "auth != null",
".write": "auth != null"
}
},
当我将读取权限更改为 true 时,它会起作用。
我可以使用什么规则来仅允许登录的匿名用户(和注册的登录用户)读取我的数据?
最佳答案
您的代码会在用户登录之前附加监听器。首次附加监听器时,Firebase 数据库服务器会立即检查权限,因此会立即拒绝未经授权的监听。
解决方案是等到用户通过身份验证后再附加监听器:
$(document).ready(function () {
var config = {
apiKey: "<my api key>",
authDomain: "<my firebase>.firebaseapp.com",
databaseURL: "https://<my firebase>.firebaseio.com",
storageBucket: "<my firebase>.appspot.com"
};
firebase.initializeApp(config);
firebase.auth().onAuthStateChanged(function (user) {
if (user) {
var ref = new Firebase("https://<my firebase>.firebaseio.com/offices/some_office");
ref.on("value", function (snapshot) {
var name = snapshot.child("title").val();
console.log(snapshot.val());
}, function (errorObject) {
console.log("The read failed: " + errorObject.code);
});
} else {
firebase.auth().signInAnonymously();
}
});
});
顺便说一句:我强烈建议您还将 Firebase 数据库的代码更新到版本 3.x。
关于javascript - 针对用户匿名登录的 Firebase 规则,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41272968/