【问题标题】:Firestore security rules not working on specific fieldFirestore 安全规则不适用于特定领域
【发布时间】:2019-04-06 11:32:57
【问题描述】:

规则:

match /transactions/{transaction} {
  allow read: if request.auth.uid == resource.data.user_id;
}

数据库:

ts 文件:

 this.transCollection = afs.collection<Transaction>('transactions',ref => ref.where('cust_id', '==', this.cust_id).orderBy('created','desc'));
     this.transactions = this.transCollection.snapshotChanges().pipe(
       map(actions => actions.map(a => {
         const data = a.payload.doc.data() as Transaction;

         const id = a.payload.doc.id;
         return { id, data };
       }))
     );

错误: core.js:1673 ERROR 错误:权限缺失或不足。

【问题讨论】:

  • 请更新您的问题以包含可以触发此错误的最少代码。
  • 代码在没有安全规则的情况下运行良好@FrankvanPuffelen

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


【解决方案1】:

安全规则不会自行过滤数据。相反,安全规则只允许保证只会匹配允许的文档的查询。如果查询有可能返回不允许的文档,安全规则会立即拒绝该查询。

您的查询过滤cust_id,而规则允许/禁止user_id。这意味着您的查询正在尝试检索您无权访问的文档。由于您的查询可能会返回带有错误 user_id 的文档,因此规则会拒绝该查询。见https://firebase.google.com/docs/firestore/security/rules-query

我的最佳猜测是你希望你的规则也匹配cust_id

allow read: if request.auth.uid == resource.data.cust_id;

通过这些规则,它们匹配查询的条件,因此将允许读取/侦听器。

【讨论】:

  • 没有 cust_id 与 uid 不同,我需要带有 cust_id 的数据过滤器,但还需要检查 user_id 是否与当前用户 id 匹配,以便用户只能访问他的客户。
  • 但是用户可以为cust_id 传递他们想要的任何值,不是吗?因此,在这种情况下,安全规则无需强制执行,它只是一个查询参数。
【解决方案2】:

得到解决方案,条件没有问题,但在基于字段条件的 uid 需要允许来自经过身份验证的用户的请求,然后读取 user_id 是否与当前 uid 匹配:

// Allow a read if request user id is same as resourse user_id
    allow read: if request.auth.uid == resource.data.user_id;

规则:

match /transactions/{transaction} {
  allow read: if request.auth.uid == resource.data.user_id;
}

ts 文件:

//Add user_id in where condition 
this.transCollection = afs.collection<Transaction>('transactions',ref => ref.where('user_id', '==', this.user_id).where('cust_id', '==', this.cust_id).orderBy('created','desc'));
     this.transactions = this.transCollection.snapshotChanges().pipe(
       map(actions => actions.map(a => {
         const data = a.payload.doc.data() as Transaction;

         const id = a.payload.doc.id;
         return { id, data };
       }))
     );

【讨论】:

    猜你喜欢
    • 2021-03-30
    • 1970-01-01
    • 1970-01-01
    • 2019-03-03
    • 2021-01-04
    • 2021-09-10
    • 2021-05-14
    • 1970-01-01
    • 2018-10-19
    相关资源
    最近更新 更多