关于 javascript:如何从客户端安全地写入 Firebase?

How to Write Securely to Firebase from a Client?

我可以理解如何从服务器写入 Firebase 并包含用户身份验证令牌等。但我想知道是否有一种方法可以为登录用户直接从客户端安全地连接到 Firebase。

背景 - 上下文

Firebase 库提供了如下所示的 set() 方法以允许写入实时数据库,但似乎没有任何方法可以保证安全。为了在客户端中使用此代码,需要包含数据库凭据。

1
2
3
4
5
6
7
function writeUserData(userId, name, email, imageUrl) {
  firebase.database().ref('users/' + userId).set({
    username: name,
    email: email,
    profile_picture : imageUrl
  });
}

问题

无论如何可以将用户"身份验证令牌"从客户端直接发送到 Firebase?

我是否需要使用其余 API 并在标头中提供它,或者我是否缺少关于 set() 方法的某些内容?


Firebase 规则可让您从客户端安全地连接 Firebase。

第 1 步:在 firebase 数据库规则中设置规则,如下所示。

1
2
3
4
"rules": {
".read":"auth!=null", //
".write":"auth!=null" // it will not allow user to write until they are logged in.
};

第 2 步:您也可以像下面这样设置树级别的规则

1
2
3
4
5
6
7
8
"rules":{
"users":{
 "$uId":{ // your user Id
   ".read":"auth.uid===$uId",
     ".write":"auth.uid===$uId",
  }
 }
}

Firebase

Firebase 规则文档