【问题标题】:Setup Firestore User Security Rule设置 Firestore 用户安全规则
【发布时间】:2019-09-15 07:25:08
【问题描述】:

我是 Firestore 的新手,我正在尝试设置简单的安全规则,以便只有登录的人才能创建新的数据库条目,而用户只能读取和写入自己的条目。

service cloud.firestore {
  match /databases/{database}/documents {
    match /Users/{userID} {

      // Can only create a new entry if signed in with a uid. 
      allow create: if request.auth.uid != null;

      // Can only update an entry if signed in with uid and changing own information (saved under uid)
      allow update: if request.auth.uid != null &&
        userID == request.auth.uid;

      // Can only read (get/list) an entry if signed in with uid and reading own information (saved under uid)
      allow read: if request.auth.uid != null &&
        resource.data.userID == request.auth.uid;
}

} }

create new entry case 工作正常,但我想知道这是否足够安全。

对于更新和阅读,我还想检查用户是否正在更新/阅读他们自己的条目。文档名称是来自 Firebase 的 uid(也就是 UserID),因此只需检查 request.auth.uid 是否相同就可以了,但是我编写它的方式有些不对劲。调用被阻止,当我在模拟器中运行它时出现错误:缺少权限或权限不足。查看文档和tutorial video 后,我无法弄清楚。

【问题讨论】:

  • 您所说的“有事发生了”是什么意思?你的问题到底是什么?
  • 我更新得更清楚了。你怎么看?

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


【解决方案1】:

以下内容应该足以满足您的情况:

// True if the user is signed in or the requested data is 'public'
function signedInOrPublic() {
  return request.auth.uid != null || resource.data.visibility == 'public';
}

// Make sure the uid of the requesting user matches name of the user
// document. The wildcard expression {userId} makes the userId variable
// available in rules.
match /users/{userId} {
  allow read, update, delete: if request.auth.uid == userId;
  allow create: if signedInOrPublic();
}

【讨论】:

  • 感谢您的帮助!在我的情况下,我有 request.auth.uid == userID 。我在 userID 下还有另一个集合,我必须在 /Users/{userID} 下设置一组单独的规则。
  • 很高兴听到它有帮助。 Firestore 的优点在于默认情况下拒绝访问,您需要非常明确可以访问哪些区域 - 这样您就可以在授予访问权限的位置感到相对安全。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-10-19
  • 2019-07-05
  • 1970-01-01
  • 2018-08-17
  • 2020-06-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多