Firestore规则配置异常:授权用户要么全览数据要么无权限
Firestore规则授权问题解决
你的Events集合文档结构包含userId、eventTitle、eventLocation等字段,其中userId字段存储文档所属用户的UID。目前你配置的Firestore规则要么允许授权用户查看所有数据,要么完全无法查看,核心原因和解决方案如下:
问题原因
你对Firestore安全规则的核心逻辑理解有误:Firestore安全规则不是过滤器。当执行集合级查询(比如直接拉取整个Events集合)时,Firestore不会逐个检查文档是否符合规则再返回,而是先判断该查询是否有可能返回不符合规则的文档,若存在这种可能则直接拒绝整个请求。
你尝试的第二条规则要求request.auth.uid == resource.data.userId,但查询未添加任何过滤条件,Firestore判定该查询可能获取到其他用户的文档,因此直接拒绝请求,导致你看不到任何数据。
解决方案
1. 保留安全规则逻辑
规则本身的权限判断是正确的,无需修改:
rules_version = '2'; service cloud.firestore { match /databases/{database}/documents { match /Events/{docId} { allow read, write: if request.auth != null && request.auth.uid == resource.data.userId; } } }
2. 修改查询代码,添加用户ID过滤
必须在查询中添加userId等于当前用户UID的过滤条件,让Firestore验证该查询只会返回符合规则的文档,从而允许请求:
body: StreamBuilder( stream: FirebaseFirestore.instance .collection("Events") .where("userId", isEqualTo: FirebaseAuth.instance.currentUser!.uid) // 添加用户ID过滤 .orderBy("date", descending: false) .snapshots(), builder: (context, snapshot) { if (snapshot.hasData) { return ListView.builder( itemCount: snapshot.data!.docs.length, itemBuilder: (context, index) { final post = snapshot.data!.docs[index]; return EventCard( titleEvent: post['eventTitle'], locationEvent: post['eventLocation'], dateEvent: post['date'], timeHour: post['timeHour'], timeMinute: post['timeMinute'], ); }, ); } else if (snapshot.hasError) { return Center( child: Text('Error${snapshot.error}'), ); } return const Center( child: CircularProgressIndicator(), ); }, ),
注意事项
- 确保
Events集合中每个文档的userId字段值与用户UID完全一致(大小写、格式均匹配)。 - 可使用Firebase控制台的规则模拟器测试不同用户场景下的规则生效情况,排查问题更高效。
内容的提问来源于stack exchange,提问作者Mutant52
相关产品推荐
相关产品推荐

