【问题标题】:Let user access to their own data in firebase让用户在 firebase 中访问自己的数据
【发布时间】:2018-07-04 03:37:06
【问题描述】:

我有每个数据关联的用户,

规则定义如下-

{
  "rules": {
    ".read": false,
    ".write": false,
    "expenses": {
      ".read": "auth.uid === data.child('userId').val()",
      ".write": "auth.uid === data.child('userId').val()"
    },
    "categories": {
        ".read": "auth != null",
        ".write": "auth != null"
    }
  }
}

我有一个要求,用户只能读取与其 userId 关联的数据。

获取数据的函数-

getExpense():AngularFireList<ExpenseData>{
   if (!this.userId) return;
   this.expenses = this.db.list(`expenses`);
   return this.expenses
}



getCategory():AngularFireList<CategoryData>{
   if (!this.userId) return;
   this.categories = this.db.list('categories');
   return this.categories;
}

错误:

错误错误:permission_denied at /expenses:客户端无权访问所需数据。

【问题讨论】:

  • 请分享引发此错误的实际代码。
  • 嗨 Frank van Puffelen,我添加了从火力基地获取数据的功能。感谢您的回复。

标签: firebase-realtime-database firebase-authentication angularfire2 firebase-security


【解决方案1】:

您似乎正在尝试读取/expenses,但这是访问/expenses 的条件:

".read": "auth.uid === data.child('userId').val()",

由于没有/expenses/userId,所以没有人可以访问/expenses。如果您添加带有 UID 的 /expenses/userId,则具有该 UID 的用户将可以访问所有 /expenses,而不仅仅是他们自己的。

请注意,安全规则不能用于过滤数据,我认为您正在尝试这样做。这个主题之前已经很多讨论过了,所以我建议你查看一些questions that mention "rules are not filters"

几个月后就可以完成您的方案。但是您需要同时执行两个步骤:

  1. 确保从您的代码中只查询允许的子节点。
  2. 使用您的规则来验证查询是否仅访问允许的数据。

请参阅documentation on query-based rules。从那里:

代码:

db.ref("baskets").orderByChild("owner")
                 .equalTo(auth.currentUser.uid)
                 .on("value", cb)     

规则:

"baskets": {
  ".read": "auth.uid != null &&
            query.orderByChild == 'owner' &&
            query.equalTo == auth.uid" // restrict basket access to owner of basket
}

【讨论】:

    猜你喜欢
    • 2019-09-24
    • 2017-10-29
    • 2016-06-19
    • 1970-01-01
    • 2019-09-21
    • 1970-01-01
    • 2016-09-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多