firebase - 快照侦听器:FirebaseError:权限缺失或不足

时间:2021-03-24 07:29:51

标签: reactjs firebase firebase-realtime-database google-cloud-firestore

我有一个无法解决的 Fairbase 问题。 我想在 React 中使用 Firebase,但出现此错误: “快照侦听器:FirebaseError:权限缺失或不足。”

这是我运行的 Fairbase 命令:

firebase.js:

import firebase from "firebase/app";
import "firebase/firestore";

const firebaseConfig = {
    apiKey: "AIz********cVU",
    authDomain: "so******.com",
    projectId: "soc*****468b",
    storageBucket: "so******ot.com",
    messagingSenderId: "12*****87",
    appId: "1:12*****12",
    measurementId: "G*****X1"
};

firebase.initializeApp(firebaseConfig);
export default firebase;

聊天组件 - 这里我使用了 firebase:

class chat extends Component {
    
    componentDidMount() {
        this.test();
    }


    test = () => {
        const ref = firebase.firestore().collection("users");
        ref.onSnapshot((querySnapshot) => {
            const items = [];
            querySnapshot.forEach((doc) => {
                items.push(doc.data());
            })
            console.log(items)
        })

    }

    render() {

        return (

            <section>
               <div>CHAT</div>
            </section>
        );
    }
}

这些是我目前在 Firebase 中的规则

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read, write: if request.auth != null;
    }
  }
}

当我像这样更改规则时:

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      //allow read, write: if request.auth != null;
      allow read, write: if true;
    }
  }
}

它有效,但我真的不希望它被打开,我不希望任何人能够访问我的 Firebase。

我很乐意帮忙,我已经坐了几天了,拜托了。

谢谢

1 个答案:

答案 0 :(得分:1)

您已使用 firebaseConfig 初始化应用程序,但这并不意味着您已通过身份验证以发出请求,而且您的 Firebase 规则规定仅启用读写 if request.auth != null,这意味着如果您有一个经过身份验证的用户发出请求,您将被锁定在 Firestore 之外。

因此,为了解决您需要使用 Firebase 实施身份验证才能查询 Firestore 的问题,我建议您查看此 documentation 中使用电子邮件和密码登录的示例,同一文档中还提供了 Google 登录、Facebook 登录、匿名登录等的链接,因此您可以查看哪一个更适合您的应用需求。