如何在Firebase安全规则中访问Firestore文档内的字段变量?
Firestore 安全规则实现方案
你需要的权限控制逻辑可以通过如下规则实现,同时兼容新建、修改、删除三类写入操作的校验需求:
rules_version = '2'; service cloud.firestore { match /databases/{database}/documents { // 匹配posts集合下的所有文档 match /posts/{postId} { // 新建文档校验:要求提交的uid是当前登录用户的uid allow create: if request.auth != null && request.resource.data.uid == request.auth.uid; // 更新/删除文档校验:要求当前用户uid和文档已存储的uid一致 allow update, delete: if request.auth != null && resource.data.uid == request.auth.uid; } } }
规则字段说明
request.auth:当前发起请求的登录用户身份对象,非空校验可拦截未登录用户的写入请求request.resource.data:本次请求提交的完整文档数据,新建文档时通过该对象读取用户提交的uid字段resource.data:posts集合中被操作的已存在文档的原始数据,修改、删除操作时通过该对象读取文档存储的uid字段
如果你只需要校验修改、删除场景,不需要限制新建文档的uid归属,可以直接合并write权限规则:
match /posts/{postId} { allow write: if request.auth != null && resource.data.uid == request.auth.uid; }
内容的提问来源于stack exchange,提问作者Trev347
相关产品推荐
相关产品推荐

