Firestore 规则不适用于 userId

Wil*_*iam 6 firebase google-cloud-firestore

我有一个简单的集合用户,文档 id 使用带有名称字符串的 uid 在此输入图像描述

我正在使用 angularfire2 连接到集合

this.users = afs.collection<User>('users').valueChanges();
Run Code Online (Sandbox Code Playgroud)

我正在使用 firebase 身份验证。显示用户 ID 时,我得到 4NxoeUeB4OXverhHhiw86eKl0Sj1 ,它与用户文档匹配。

this.afAuth.authState.subscribe(auth => console.log(auth.uid));
Run Code Online (Sandbox Code Playgroud)

我正在尝试为集合添加规则。如果我使用下面的规则,我会收到错误“缺少或权限不足”。

`service cloud.firestore {
  match /databases/{database}/documents {
    match /users/{userId} {
        allow read, write: if request.auth.uid == userId;
    }
  }
}`
Run Code Online (Sandbox Code Playgroud)

如果我将规则更改为 request.auth != null 则会显示数据。

`service cloud.firestore {
  match /databases/{database}/documents {
    match /users/{userId} {
        allow read, write: if request.auth != null;
    }
  }
}`
Run Code Online (Sandbox Code Playgroud)

我可能做错了什么?我也在尝试一些不同的规则,例如。resource.data.name != null。它也不起作用。

我正在测试规则。最终结果我想要一个 reader 数组字段和 writers 数组字段,这样我就可以尝试request.auth.uid in resource.data.readers控制对文档的访问

Rem*_*emi 5

您正在尝试获取/users/*,但您只能访问/users/{yourid}

您应该只检索您有权访问的数据,因此即使您实际上只有一个文档,也需要过滤查询。

// either by adding a field in your doc
afs.collection('users', ref => ref.where('id', '==', auth.uid))

// or by getting the document directly
afs.collection('users').doc(auth.uid)
Run Code Online (Sandbox Code Playgroud)

对查询执行规则检查时,Cloud Firestore 安全规则将进行检查,以确保用户 在执行查询之前有权访问所有结果。如果查询可能返回用户无权访问的结果,则整个查询将失败并且 Firestore 将返回错误。

来源: https: //cloud.google.com/firestore/docs/security/secure-data#shallow_queries

  • 哇,我花了几个小时试图解决这个问题!令人发狂。我希望我的客户可以只问“给我这个集合中我有权访问的所有文档”,服务器只会返回那些符合规则的文档...而不是我必须构建确切的 where 子句来匹配规则提前时间。呃…… (2认同)