我在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时,它可以正常工作。
我可以使用什么规则来仅允许匿名用户(和已注册的登录用户)登录才能读取我的数据?
答案 0 :(得分:1)
您的代码在用户登录之前附加了一个侦听器.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版。