首页 > 解决方案 > 如何只允许管理员应用写入 Firebase?

问题描述

我有两个独立的应用程序,一个应用程序适用于只能读取 firebase 数据库和存储的普通用户,另一个应用程序用于将数据上传到 firebase。我已经打开了firebase规则“读取,写入=真”。我只需要允许管理/上传应用程序将数据上传到数据库和存储(如果可以使用一些简单的管理应用程序ID)。

我已经看过的帖子:

how-to-only-allow-one-admin-user-to-write-firebase-database allowed -specific-user-write-access

标签: javaandroidfirebasefirebase-realtime-database

解决方案


第1步:您必须授权某个用户。为此,请转到: 开发 -> 身份验证 -> 添加用户

第 2 步:您必须在 Firebase 中设置规则。

转到数据库-> 规则并授予特定用户更改数据库的访问权限。

这是用户更改“令牌”字段的一组规则示例:

{
"rules": {
"Tokens" : {
"$uid": {
".read": true,
".write": "auth.uid === $uid"
   }
  }
 }
}

JavaScript 代码示例:

var email = "XXX@XXX.XXX; //The user that you authenticated in Firebase
var password = XXXXXXXXXXX; //Password of that user
var uidValue = XXXXXXXXX;
const auth = firebase.auth();
//Sign in
const promise = auth.signInWithEmailAndPassword(email, password);
promise.catch(e => console.log(e.message));

//Add a realtime authentication listener
firebase.auth().onAuthStateChanged(firebaseUser => {
    if (firebaseUser) {
        const rootRef = firebase.database().ref();
        const usersRef = rootRef.child('Tokens');
        const uid = uidValue;
        const daveRef = usersRef.child(uid);
        daveRef.set({
            id: 232 //New ID
        });

    }
    else {
        console.log("not logged in");
    }
});
firebase.auth().signOut();

最后,firebase 实时数据库具有以下字段:

"Tokens" : {
"[UID value (e.g: 123XXX)]" : {
  "id" : "164"
  }
 }

推荐阅读