【问题标题】:Cloud Firestore with Authentication具有身份验证的 Cloud Firestore
【发布时间】:2018-05-02 08:17:52
【问题描述】:

我一直在寻找一种在 Firebase 的新 Cloud Firestore 中使用身份验证的方法。我知道这是可能的,但在文档和其他地方都没有好的指南。

有人可以解释当get()来自 Cloud Firestore 的数据时如何提供身份验证 UID?

这是我的安全规则:

service cloud.firestore {
  match /users/{userID} {
    allow read, write: if request.auth.uid == userID;
  }
}

这是我当前的代码:

var db = firebase.firestore();
var docRef = db.collection("users").doc(uid); //lets say "uid" var is already defined
docRef.get().then(function(doc) {
  if (doc.exists) {
      console.log("Document data:", doc.data());
  } else {
      console.log("No such document!");
  }
}).catch(function(error) {
  console.log("Error getting document:", error);
});

我的数据库的结构只是根目录下的“用户”集合,然后是每个用户的文档(以 UID 命名)。我想获取带有用户 UID 的文档。

当然,由于安全规则的原因,这会产生“权限缺失或权限不足”错误,这是意料之中的。

这个问题可能看起来很简单,但如果有人能找到一些很好的文档,那就太好了!

【问题讨论】:

  • 你想获取所有用户还是只获取你的用户。
  • 请提供MCVE(阅读链接,它非常有用)。例如。 docRef 指向什么?您正在为用户登录吗?
  • @FrankvanPuffelen 好的,我编辑了问题以填写缺失的信息。是的,我已经通过 Google 完成了身份验证。我有 UID,我只需要知道如何处理它
  • @Hareesh 我添加了有关我的数据库结构的信息。我在根目录有一个“用户”集合,其中包含文档(以 UID 命名)。我想让具有相应 UID 的用户访问他们自己的文档。
  • 好的,你是如何将你的 cities 收藏链接到 users 的?

标签: javascript firebase authentication firebase-authentication google-cloud-firestore


【解决方案1】:

您的规则应该在match /databases/{database}/documents

service cloud.firestore {
  match /databases/{database}/documents {
    match /users/{userID} {
        allow read, write: if request.auth.uid == userID;
   }
  }
}

【讨论】:

    【解决方案2】:

    我只是对 UID 的工作方式感到困惑。我的印象是您必须为数据库操作提供 UID 和身份验证令牌。

    您实际上并没有将 UID 传递给数据库操作。 firebase 对象存储身份验证状态。您只需登录(check the Firebase docs to read how to do this),操作完成后(使用.thenpromise 语句)即可进行操作。

    此外,要让用户在每次访问您的应用时都不登录,您可以have the `firebase object's authentication state persistent

    【讨论】:

    • 这样做安全吗?正如您所解释的那样,它并不是真正的身份验证:/
    • @BMX 是的。在幕后,当您调用登录方法时,会生成 Oauth ID 和刷新令牌。在执行安全规则之前,Firebase 会确保幕后 JWT 令牌有效。
    猜你喜欢
    • 1970-01-01
    • 2020-10-16
    • 1970-01-01
    • 1970-01-01
    • 2018-06-22
    • 1970-01-01
    • 2019-11-22
    • 2019-03-23
    • 2020-05-22
    相关资源
    最近更新 更多