You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Firestore用户组权限规则异常:权限不足问题排查

Firestore安全规则权限异常排查与解决

场景说明

Firebase Firestore中存在ShoppingLists和Users两个集合,Users集合的文档ID与用户uid一一对应。为限制文档读写权限,配置了安全规则,模拟器验证规则逻辑正确,但实际调用查询时触发FirebaseError: Missing or insufficient permissions异常,添加authorizedGroup字段的查询条件后恢复正常。

配置的Firestore安全规则

service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read: if request.auth != null 
                  && resource.data.authorizedGroup == get(/databases/$(database)/documents/users/$(request.auth.uid)).data.group;
      
      allow write: if request.auth != null 
                   && resource.data.authorizedGroup == get(/databases/$(database)/documents/users/$(request.auth.uid)).data.group;
    }
  }
}

触发异常的查询代码

async getActiveList(): Promise<ShoppingList> {

    // 能正确打印当前用户信息
    this.authService.user$.subscribe(u => console.log(u)); 

    const q = query(this.shopListCollection, 
                    where("isActive", "==", true), 
                    // 注释掉这个条件时会触发权限异常
                    // where("authorizedGroup", "==", users.group), 
                    limit(1));

    // 这一行触发权限异常
    const docsSnapshots = (await getDocs(q)).docs; 

    // 后续代码无法执行
    if (docsSnapshots.length > 0) {
      const data = docsSnapshots[0].data() as ShoppingList;

      // 新列表项置顶排序
      data.items.sort(this.compareCreatedOn);
      return data;
    }

    return null as ShoppingList;
}

问题原因与解决方法

Firestore安全规则的核心原则是规则不是过滤器——规则不会帮你过滤掉不符合条件的文档,而是会直接拒绝整个查询,除非你能证明查询返回的所有文档都必然符合规则要求。

在这个场景中,安全规则要求文档的authorizedGroup必须等于当前用户的group字段,但如果查询中没有显式添加where("authorizedGroup", "==", users.group)这个条件,Firestore无法提前确认查询结果里的每一条文档都满足权限要求,因此会直接拒绝查询请求。

解决方法就是在查询中添加与安全规则匹配的authorizedGroup条件,让Firestore能够验证查询范围完全在允许的权限范围内,此时查询即可正常执行。

内容的提问来源于stack exchange,提问作者Francesco

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 19:22:48