google-cloud-firestore - 定义正确的 Firestore 安全规则
问题描述
我是 Firebase Firestore 的新手,我想定义安全规则。如图所示,我的数据结构非常简单。
每个用户都有自己的带有子集合的文档。我希望用户只能读写他自己的文档(包括子集合中的文档),所以我的规则应该是这样的:
service cloud.firestore {
match /databases/{database}/documents {
match /users/{userId} {
allow read, update, delete: if request.auth != null && request.auth.uid == userId;
allow create: if request.auth != null;
}
}
}
使用此代码,用户是否也可以读取和写入子集合中的文档?还有什么重要的我需要添加到安全规则中或者这就是我需要做的吗?
解决方案
规则中的match
语句控制这些规则适用的内容。在你的情况下:
match /users/{userId} {
此规则适用于users
集合本身中的文档,而不适用于子集合中的文档。
如果您也想对所有子集合应用相同的规则,您可以使用递归通配符匹配( =**
),如下所示:
match /users/{userId=**} {
不是这样,相同的规则适用于users
集合中的文档,以及那里的所有子集合/文档。
您还可以通过为子集合嵌套match
子句来更精细地控制对子集合的访问。例如,假设您有一个子集合messages
,并且您只想允许用户读取该子集合的访问权限,您可以使用以下规则来实现:
match /users/{userId} {
allow read, update, delete: if request.auth != null && request.auth.uid == userId;
allow create: if request.auth != null;
match /messages/{messageId} {
allow read: if request.auth != null && request.auth.uid == userId;
}
}
如您所见,我们在这里逐字重复条件,因此在自定义命名函数中捕获条件以提高可读性和可维护性是很常见的。
推荐阅读
- javascript - 一定时间后删除孩子,Firebase功能
- java - ftc android studio中的重复类
- spring - Spring Boot schema.sql 忽略注释(Oracle 优化器提示)
- ruby-on-rails - 有没有办法在 Rails 的单个查询中进行多次插入?
- log4j - log4j 属性文件未在 Eclipse 中更新
- php - Zf3 在 OnBootrstap() Module.php 中获取自定义服务实例 - 获取 ServiceNotFoundException 致命错误
- swift - Swift - API 返回包含不同类型的数组
- python - Python:我的代码做错了什么?
- html - 如何检测水龙头?
- java - 在Java中,我可以让父类实现一个使用子类变量的方法吗?