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

Firebase权限不足问题:自定义Firestore规则失效如何修复?

Firestore规则配置问题排查与修复

问题场景

需求为:允许所有用户读取数据,仅管理员可执行更新、删除及写入新数据。配置自定义Firestore规则后功能完全失效,规则实验室测试正常,但实际调用触发FirebaseError: Missing or insufficient permissions;使用开放全权限的规则可正常运行。

当前规则代码

rules_version = '2';

service cloud.firestore {
  match /databases/{database}/documents {
    match /documents/{collectionName} {
       allow update, delete, write: if isAdmin();
       allow read: if true;
    }
    
    function isLoged() {
        return request.auth != null && request.auth.uid != null
    }
    
    function isAdmin() {
      return isLoged() && get(/databases/$(database)/documents/users/$(request.auth.uid)).data.role == "ADMIN";
    }
  }
}

前端调用代码

import { initializeApp } from 'firebase/app'
import { getFirestore, collection, getDocs } from 'firebase/firestore'

// 你的Firebase项目配置
const firebaseConfig = { ... };

const app = initializeApp(firebaseConfig);

// Firestore引用
const db = getFirestore(app)

export const animesCollection = collection(db, 'animes')

console.log({ docs: (async () => await getDocs(animesCollection))() })

全权限测试规则(可正常运行)

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read, write: if true;
    }
  }
}

问题根源

当前规则的路径匹配错误:规则中写的是match /documents/{collectionName},实际要访问的集合是animes(顶层集合),规则根本没匹配到目标集合,导致所有请求被拒绝。

修复方案

修正后的完整规则

rules_version = '2';

service cloud.firestore {
  match /databases/{database}/documents {
    // 匹配所有顶层集合及下属所有文档
    match /{collectionName}/{document=**} {
       // 开放所有用户读取权限
       allow read: if true;
       // 仅管理员可执行创建、更新、删除操作
       allow create, update, delete: if isAdmin();
    }
    
    function isLoggedIn() {
        return request.auth != null && request.auth.uid != null;
    }
    
    function isAdmin() {
      return isLoggedIn() && get(/databases/$(database)/documents/users/$(request.auth.uid)).data.role == "ADMIN";
    }
  }
}

关键调整点

  1. 路径匹配修正:将错误的/documents/{collectionName}改为/{collectionName}/{document=**},覆盖所有顶层集合(如animes)及其子文档。
  2. 权限动作明确化:拆分原规则的write为create, update, delete,Firestore中write本身包含这三个动作,拆分后更贴合需求表述。
  3. 函数名规范:修正拼写错误,将isLoged改为isLoggedIn。

可选优化

如果仅需针对特定集合(比如只限制animes和users),可以指定集合列表:

match /animes/{document=**}, /users/{document=**} {
  allow read: if true;
  allow create, update, delete: if isAdmin();
}

验证要点

  • 确认users集合中管理员用户的role字段值为"ADMIN"(大小写严格匹配)。
  • 管理员执行写操作时,必须已通过Firebase Auth完成登录。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 16:23:10