【问题标题】:Firestore rules not working for userIdFirestore 规则不适用于 userId
【发布时间】:2018-04-02 06:22:48
【问题描述】:

我有一个简单的用户集合,文档 id 使用带有名称字符串的 uid

我正在使用 angularfire2 连接到集合

this.users = afs.collection<User>('users').valueChanges();

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

this.afAuth.authState.subscribe(auth => console.log(auth.uid));

我正在尝试为集合添加规则。如果我使用以下规则,我会收到错误 Missing or enough permissions。

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

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

`service cloud.firestore {
  match /databases/{database}/documents {
    match /users/{userId} {
        allow read, write: if request.auth != null;
    }
  }
}`

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

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

【问题讨论】:

    标签: firebase google-cloud-firestore


    【解决方案1】:

    您正在尝试获取/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)
    

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

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

    【讨论】:

    • 感谢 Remi 的回答,我想我了解规则所需的内容,现在可以更好地查询。如果 Firestore 查询能够实现像 Lotus Notes 这样的访问控制,那将是非常棒的。例如,如果我查询标准用户集合,它只会返回我有权访问的文档。不需要专门为我有权访问的文档构建查询。
    • 哇,我只是花了几个小时试图弄清楚这一点!令人抓狂。我希望我的客户可以只问“给我这个集合中我可以访问的所有文档”并且服务器只会返回那些匹配规则的......而不是我必须构建确切的 where 子句来匹配规则提前时间。咕噜……
    猜你喜欢
    • 1970-01-01
    • 2021-03-30
    • 2020-05-28
    • 2019-04-06
    • 1970-01-01
    • 2021-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多