至于 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/