Firestore子集合ServiceLocations读取权限验证失败求助
问题排查与解决方法
1. 子集合规则存在语法错误
你的ServiceLocations子集合规则中缺少if关键字,这会导致Firestore规则解析失败,默认拒绝所有请求。修正后的规则如下:
match /Customers/{customerId} { allow read, update, create, delete: if request.auth != null && get(/databases/$(database)/documents/Users/$(request.auth.uid)).data.businessId in resource.data.businessIds || request.auth != null && request.auth.uid == resource.data.uid || request.auth != null && get(/databases/$(database)/documents/Users/$(request.auth.uid)).data.businessId == resource.data.businessId || request.auth != null && get(/databases/$(database)/documents/Users/$(request.auth.uid)).data.customerId == resource.data.customerId; match /ServiceLocations/{ServiceLocationId} { // 补充if关键字,修正语法 allow read, update, create, delete: if request.auth != null && get(/databases/$(database)/documents/Users/$(request.auth.uid)).data.businessId == resource.data.businessId; } }
2. 查询未添加匹配规则的过滤条件
当通过onSnapshot查询整个子集合时,Firestore需要提前验证所有可能返回的文档是否符合规则。你的规则要求resource.data.businessId等于用户的businessId,但查询代码未添加对应过滤条件,Firestore无法在查询阶段确认所有文档满足条件,因此拒绝请求。
修改查询代码,添加过滤逻辑:
// 先获取当前用户的businessId db.collection("Users").doc(request.auth.uid).get().then(userDoc => { const userBusinessId = userDoc.data().businessId; db.collection("Customers") .doc(selectedCustomerData.customerId) .collection("ServiceLocations") .where("businessId", "==", userBusinessId) // 添加匹配规则的过滤条件 .onSnapshot((snapshot) => { // 处理快照数据 }); });
3. 顶级规则的逻辑运算符优先级问题
你的Customers集合规则中,&&和||组合未加括号,因&&优先级高于||,会导致条件判断与预期不符。建议给每组条件添加括号明确逻辑关系:
match /Customers/{customerId} { allow read, update, create, delete: if (request.auth != null && get(/databases/$(database)/documents/Users/$(request.auth.uid)).data.businessId in resource.data.businessIds) || (request.auth != null && request.auth.uid == resource.data.uid) || (request.auth != null && get(/databases/$(database)/documents/Users/$(request.auth.uid)).data.businessId == resource.data.businessId) || (request.auth != null && get(/databases/$(database)/documents/Users/$(request.auth.uid)).data.customerId == resource.data.customerId); // 子集合规则... }
4. 检查Users集合的读取权限
规则依赖get操作获取当前用户的Users文档数据,如果Users集合未开放对应读取权限,该get操作会失败,导致条件不成立。确保Users集合规则如下:
match /Users/{userId} { allow read, write: if request.auth != null && request.auth.uid == userId; }
内容的提问来源于stack exchange,提问作者CodingIsFun33
相关产品推荐
相关产品推荐

