【问题标题】:Cannot get data from real time database with anonymous authentication (React Native) - Permission Denied无法通过匿名身份验证(React Native)从实时数据库获取数据 - 权限被拒绝
【发布时间】:2020-04-16 23:47:02
【问题描述】:

我正在尝试在我的应用中实现匿名身份验证。我已经使用 React Native Firebase (https://rnfirebase.io/) 完成了它。到目前为止,注册情况良好。用户注册后,我获得了该特定案例的用户 ID。这是我的代码:

const authenticate = async () => {
    await auth()
      .signInAnonymously()
      .then(() => {
        console.log('User signed in anonymously');
        console.log(user);
        firebase.auth().onAuthStateChanged(user => {
          if (user != null) {
            fetchData();
          }
        });
      })
      .catch(error => {
        if (error.code === 'auth/operation-not-allowed') {
          console.log('Enable anonymous in your firebase console.');
        }
        setFetching(false);
        console.error(error);
      });
  };

如您所见,如果您在注册成功时检查该部分,我们有一个名为 fetchData() 的函数。这个函数从实时数据库中检索我的数据。这里是:

  const fetchData = async () => {
    try {
      await fetch(setLocale())
        .then(response => response.json())
        .then(responseJSON => {
          saveFavoritesFromAsync(responseJSON);
          setFetched(true);
          setFetching(false);
          fetchMedusa();
        });
    } catch (error) {
      console.log(error);
      setFetching(false);
    }
  };

当我在 firebase 中实施规则时,问题就来了。在此之前,我将所有内容都打开(读取:true,写入:true),但为了增加一点安全性,我正在尝试添加此匿名身份验证。我现在的规则是:

{
  "rules": {
    ".read": "auth != null",
    ".write": "auth != null"
  }
}

一旦我设置了这个规则,就无法检索数据。我基本上没有得到任何数据,我的控制台日志显示“权限被拒绝”。

我做错了什么?我应该将用户 ID 与 fetch 一起传递吗?请帮忙

非常感谢

【问题讨论】:

  • 我在您共享的代码中没有看到对 Firebase 实时数据库 API 的任何调用。它可能隐藏在一种辅助方法的后面,但不幸的是,如果没有看到minimal, complete/standalone code that reproduces the problem,就不可能说出失败的原因。像您的辅助函数这样的外部依赖项使得它无法提供帮助。
  • 我明白了.. 你能解释一下在另一种情况下如何将身份验证信息传递给 firebase 吗?也许它可以帮助我理解。再次感谢
  • 解决了。无论如何感谢您的回答。我已经评论了答案

标签: reactjs firebase firebase-realtime-database firebase-authentication firebase-security


【解决方案1】:

我已经解决了。

来自 React Native Firebase 的包可以一起使用。发生的事情是:

我使用的是 react native 的 fetch 方法。您必须使用他们提供的 firebase 数据库包来检索或写入数据。

看看我的 fetch 现在的样子:

 await database()
        .ref(setLocale())
        .once('value')
        .then(responseJSON => {
          if (responseJSON.error) {
            setFetching(false);
            setFetched(false);
          } else {
            saveFavoritesFromAsync(responseJSON.val());
            setFetched(true);
            setFetching(false);
            fetchMedusa();
          }

同样重要的是,responseJSON 数据必须使用 .val() 方法保存,否则将不正确。

希望对有需要的人有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-02-09
    • 1970-01-01
    • 1970-01-01
    • 2021-10-18
    • 2018-08-21
    • 1970-01-01
    相关资源
    最近更新 更多