【问题标题】:User to access only his/her document in Firestore用户只能在 Firestore 中访问他/她的文档
【发布时间】:2019-12-21 23:33:06
【问题描述】:

我正在努力设置 Firestore 规则。

根据屏幕截图,我为具有动态文档 ID 的用户收集了集合。

我正在尝试为用户设置仅访问他/她的文档的规则。

FbId 是 facebook id(因为它是我应用中的身份验证方式)

userId 是 firebase id(不确定是否重要)

这是我目前的规则:

match /users/{document=**} {
  allow read, write: if normalUser();
  }

  function normalUser() {
  return request.auth.token.firebase.sign_in_provider == "facebook.com"
  && request.auth.uid != null;
}

此规则允许经过身份验证的用户访问整个集合。

如何设置此规则?如果有什么我需要改变的结构?

更新:我不想更改用户集合的 documentid 以匹配 userid,因为我有另一个集合,其中用户可能有多个文档;所以这个解决方案并不适合所有情况。

谢谢

【问题讨论】:

    标签: google-cloud-firestore firebase-security


    【解决方案1】:

    我从应用程序获取的方法是在查询中使用 facebook id,这就是它不起作用的原因。

    我现在使用的规则:

     match /users/{userId} {
        allow update: if request.auth.uid == resource.data.userId;
     }
    

    谢谢

    【讨论】:

      【解决方案2】:

      使用用户的 Firebase 身份验证 UID 作为文档的 ID 会容易得多。 Facebook UID 在安全规则中不可用。

      如果您使用 Firebase UID,则可以编写类似于 documentation 中的规则以实现基于用户的安全性。单击并阅读上面写着“另一种常见模式是确保用户只能读取和写入自己的数据”的地方。这可能是您想要做的。

      service cloud.firestore {
        match /databases/{database}/documents {
          // 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 request.auth.uid != null;
          }
        }
      }
      

      【讨论】:

      • 除了将文档 ID 更改为与用户 ID 相同之外,还有其他方法吗?因为在另一个集合中,用户可以匹配多个文档,所以它不会与另一个集合一起使用。
      • 当然,您也可以在规则中使用 Firebase UID 检查字段的内容。文档也可以指导您。
      • 我正在尝试这样做:匹配 /users/{document=**} { 允许读取,写入:如果 request.auth.uid == request.resource.data.userId } 请求。 resource.data.userId -> 它没有从用户文档中获取 userId
      • 另一个更新:匹配 /users/{user_id} {允许读取,更新:如果 request.auth.uid == resource.data.user_id;这就是我现在正在做的事情。 user_id 是我数据库中的新字段,它具有 firebase 用户 ID。 resource.data.user_id -> 这实际上是问题所在;即使我现在尝试对其进行硬编码,它也不会从数据库中返回数据。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-31
      • 1970-01-01
      • 2021-06-08
      • 1970-01-01
      • 1970-01-01
      • 2020-11-04
      相关资源
      最近更新 更多