【问题标题】:Firebase Firestore access rules - Comparing resource dataFirebase Firestore 访问规则 - 比较资源数据
【发布时间】:2018-04-23 12:34:48
【问题描述】:

我存储在数据库中的模型是这样的:

{
    "ownerUid": <my auth UID>,
    "teamName: "Team 1",
    "teamDescription: "Team 1 desc"
}

而我的初始访问规则是这样的:

service cloud.firestore {
    match /databases/{database}/documents {    
        match /teams/{teamId} {
            allow read: if resource.data.ownerUid == request.auth.uid;
            allow write: if true; //ignore this
        }
    }
}

我为获取团队而运行的查询如下:

Query query = FirebaseFirestore.getInstance()
              .collection("teams")
              .orderBy("teamName")

运行这个查询总是会导致“PERMISSION DENIED”,我很不确定这是什么原因。

出于测试目的,我也尝试了以下规则:

allow read: if true; //Works
allow read: if request.auth.uid != null; //Works
allow read: if request.auth.uid == <my auth uid>; //Works
allow read: if resource.data.ownerUid != null; //Fails

在成功的规则上,我可以看到返回的团队中的ownerUid,并且看到它不为null,并且与匹配。

【问题讨论】:

  • 所以您希望用户只能阅读他们拥有的团队?

标签: android firebase google-cloud-firestore firebase-security


【解决方案1】:

在您当前的代码中,您正尝试从集合teams 中读取。由于您无权访问该完整集合,因此读取被拒绝。

如果您想允许用户查询他们创建的文档,您需要做两件事:

  1. 使用仅检索他们创建的文档的查询。
  2. 编写您的安全规则,以便它们允许此查询。

你已经完成了#2,但没有做#1。为了让事情顺利进行,请使用如下查询:

String uid = FirbaseAuth.getInstance().getCurrentUser().getUid();
Query query = FirebaseFirestore.getInstance()
          .collection("teams")
          .whereEqualTo("ownerUid", uid)
          .orderBy("teamName")

另请参阅Secure and query documents based on auth.uid 上的文档部分。

【讨论】:

  • 当然,这在指出时似乎很明显!这让我克服了第一个障碍,现在我只需要弄清楚如何存储团队成员,并允许他们读取访问权限。
猜你喜欢
  • 2021-05-12
  • 2021-12-27
  • 1970-01-01
  • 2020-10-19
  • 2020-08-20
  • 2020-02-24
  • 1970-01-01
  • 2018-10-10
  • 1970-01-01
相关资源
最近更新 更多