firebase - 公共(public)和私有(private)字段的 Firestore 安全规则

标签 firebase google-cloud-firestore firebase-security

至于 Firebase 实时数据库的安全规则,公共(public)数据和私有(private)数据都可以存在于同一棵树中,例如使用以下规则。

但是,在使用 Firestore 时,我们似乎无法做到这一点,因为我们可以检索的数据只是在 collection 或 document 下。
当公共(public)数据和私有(private)数据在同一个文档中定义并使用集合/文档获取数据时,如果我们不是所有者,我们会收到私有(private)数据权限不足的错误。

使用 RTDB 时,我们可以获取 'users/{userId}/publicInfo' 的数据,因为我们对集合/文档一无所知。

有什么办法可以用 Firestore 做到这一点?否则,我们应该分别进行公共(public)/私有(private)收藏吗?

// rule of Firebase Realtime Database
"users": {
   "$user_id": {
       ".read": "auth.uid === $user_id",
       ".write": "auth.uid === $user_id",

       "private": {
          ".read": "auth.uid === $user_id"   // --- private data
       }

       "public": {
          ".read": "auth !== null";           // --- public data 
       }
   }
}

// Firestore
service cloud.firestore {
  match /databases/{database}/documents {
    match /users/{userId} {

      match /{private=**} {
        allow read, write: if request.auth == userId;
      }

      match /{public=**} {
        allow read, write: if request.auth != null;
      }
    }
  }
}

最佳答案

因此,您不能为文档的单独部分设置单独的安全规则。您可以阅读整个文档,也可以不阅读。

也就是说,如果您想为您的 userID 文档提供一个“公共(public)”和“私有(private)”子集合,其中包含公共(public)和私有(private)文档,那么您完全可以这样做,而不是按照您当前设置安全规则的方式.
match /{private=**}正如您所写的那样,它并不意味着“匹配任何称为'私有(private)'的子集合”。这意味着,“无论如何匹配任何子集合,然后将其分配给一个名为 private 的变量”。文档的“Recursive matching with wildcards”部分更详细地介绍了这一点。

另外,您需要引用 request.auth.uid获取用户的 ID。

所以,你可能想要更像这样的东西:

// Firestore
service cloud.firestore {
  match /databases/{database}/documents {
    match /users/{userId} {
      // You'll probably want to add security rules around the user document 
      // itself. For now, though, let's look at our subcollections:

      match /private/{anything=**} {
        // Only the user can read documents in their private collection
        allow read, write: if request.auth.uid == userId;
      }

      match /public/{anything=**} {
        // Anybody can read documents here, as long as they're signed in
        allow read, write: if request.auth != null;
      }
    }
  }
}

关于firebase - 公共(public)和私有(private)字段的 Firestore 安全规则,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46585330/

相关文章:

node.js - Firebase Admin SDK - 创建没有密码的用户是否安全?

android - 仅使用经过身份验证的用户写入 Firebase 数据库 android

firebase - Firestore 社交媒体模型结构

firebase - Flutter:如何在Flutter中创建嵌套对象以存储在Cloud Firestore中

javascript - Firestore WEB 触发事件

javascript - 如何检索 Firebase 文档中的所有字段到 map 或 key : Value pair

firebase - 如何在 Firebase 上阻止用户?

firebase - Flutter的Firebase教程错误

firebase - 为Cloud Function指定区域时出现 “firebase.functions() takes … no argument …”异常

android - 发送数据到 Android 设备 Notification to IOS 设备