首页 > 解决方案 > 如何从客户端查询 Firestore?

问题描述

我正在为具有身份验证的 Firebase 应用程序制定安全规则。

我希望只有用户能够访问他自己的用户文档。

我有这个安全规则:

  match /users/{uid} {
  allow read, update: if request.auth.uid == uid;
  allow create: if request.auth.uid != null;
  }

但是当我运行客户端代码时,它会给出错误:

[Firestore]:状态{code=PERMISSION_DENIED,描述=缺少或权限不足。,原因=null}

在客户端代码中,我检查具有用户 uid 的文档是否已经存在(如果不存在,我将数据写入 firestore):

final QuerySnapshot result = await Firestore.instance
    .collection('users')
    .where('uid', isEqualTo: user.uid)
    .getDocuments();
documents = result.documents;
if (documents.isEmpty) {
…

为什么我会收到此错误?

我已阅读https://firebase.google.com/docs/firestore/security/rules-query并且它说db.collection("stories").where("author", "==", user.uid).get()是有效的。

标签: firebasegoogle-cloud-firestorefirebase-authenticationfirebase-security

解决方案


您的查询不符合您的规则。该查询要求所有文档字段uid与 相同的文档user.uid。但是您的规则是允许对文档 ID 与用户的 UID 相同的文档进行读取访问。这些不是一回事。查询处理的是一个名为的文档字段uid,而规则处理的是文档ID。查询和规则必须匹配。由于您没有说明文档的结构,或者您想要实现的具体目标,因此无法推荐和替代。无论如何,您的查询必须符合规则,否则每次都会失败。


推荐阅读