我的安全规则如下所示:
{
"rules": {
".read": false,
".write": "auth.user != null && newData.child('user').val() == auth.user"
}
}
基本上,没有人(管理员用户除外)可以阅读,并且用户只能在他们提供相同的用户时才能写#34;密钥,因为他们验证。
在Firebase模拟器中,一切正常。没有读取,只有经过正确认证的写入:
Attempt to write {"data":"Some Data","user":"testuser1"} to / with auth={"user":"testuser1"}
/:.write: "auth.user != null && newData.child('user').val() == auth.user"
=> true
Write was allowed.
这是我的代码(node.js):
var FirebaseTokenGenerator = require("firebase-token-generator");
var tokenGenerator = new FirebaseTokenGenerator(FIREBASE_SECRET_TOKEN);
var Firebase = require('firebase');
Firebase.enableLogging(true, true);
var userID = "testuser1";
var client = new Firebase(FIREBASE_URL);
var clientToken = tokenGenerator.createToken({user: userID});
client.auth(clientToken, function(error){
if (error){
console.log("Client login failed")
} else {
console.log("Client login success");
client.push({user: userID, data: "Some Data"}, function(error){
if (error){
console.log("Write Error: " + error);
} else {
console.log("Write success");
}
});
}
});
奇怪的是,在client.push
我收到Firebase的Permission Denied
错误。
以下是启用日志记录时Firebase库打印到日志的内容:
$ node client.js
p:0: Browser went online. Reconnecting.
p:0: Authenticating using credential: [object Object]
p:0: Making a connection attempt
c:0:0: Connection created
c:0:0:0 Websocket connecting to wss://FIREBASE_URL/.ws?v=5
c:0:0:0 Websocket connected.
c:0:0: Reset packet received. New host: REDACTED.firebaseio.com
c:0:0: Shutting down all connections
c:0:0:0 WebSocket is being closed
c:0:0:0 Websocket connection was disconnected.
c:0:0:1 Websocket connecting to wss://REDACTED.firebaseio.com/.ws?v=5&ns=REDACTED
c:0:0:1 Websocket connected.
c:0:0: Realtime connection established.
p:0: connection ready
p:0: {"r":1,"a":"auth","b":{"cred":"REDACTED_TOKEN"}}
p:0: from server: {"r":1,"b":{"s":"ok","d":{"auth":{"user":"testuser1"}}}
Client login success
r:0: set {"path":"/-JMaX2bT9IcgrN1uPBOK","value":{"user":"testuser1","data":"Some Data"},"la":null}
p:0: {"r":2,"a":"p","b":{"p":"/-JMaX2bT9IcgrN1uPBOK","d":{"data":"Some Data","user":"testuser1"}}}
c:0:0: sending ping on primary.
c:0:0: Primary connection is healthy.
p:0: from server: {"r":2,"b":{"s":"permission_denied","d":"Permission denied"}}
p:0: p response {"s":"permission_denied","d":"Permission denied"}
FIREBASE WARNING: set at /-JMaX2bT9IcgrN1uPBOK failed: permission_denied
Write Error: Error: PERMISSION_DENIED: Permission denied
我做错了什么?为什么我从模拟器和我的代码得到不同的响应?
答案 0 :(得分:1)
典型 - 现在我已将问题发布到StackOverflow,我设法解决了这个问题。
以下是我的新安全规则 - 客户端代码保持不变:
{
"rules": {
".read": false,
".write": false,
"$": {
".read": false,
".write": "auth.user != null && newData.child('user').val() == auth.user",
}
}
}