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

Firebase Firestore规则不生效,权限不足问题求助

问题排查与解决方案

背景信息

  • 数据库结构:数据库结构截图
  • 需求:已登录用户可对AddedRecipes集合进行读写操作,未登录用户仅能读取该集合

当前Firestore规则代码

service cloud.firestore {
  match /databases/{database}/documents {
    // match /{document=**} {
    //   allow read, write: if request.auth != null;
    // }
    allow read, write: if request.auth != null;
    allow read: if request.auth == null;
  }
}

报错信息

FirebaseError: Missing or insufficient permissions.

前端写入数据核心代码

import {
    initializeApp
} from "https://www.gstatic.com/firebasejs/11.1.0/firebase-app.js";
import {
    getStorage,
    ref,
    uploadBytes,
    getDownloadURL
} from "https://www.gstatic.com/firebasejs/11.1.0/firebase-storage.js";
import {
    getFirestore,
    addDoc,
    doc,
    collection
} from 'https://www.gstatic.com/firebasejs/11.1.0/firebase-firestore.js'

var firebaseConfig = {
    apiKey: "",
    authDomain: "",
    projectId: "",
    storageBucket: "",
    messagingSenderId: "",
    appId: ""
};

const app = initializeApp(firebaseConfig);
const storage = getStorage(app);
const db = getFirestore(app);

// ... 存储上传逻辑省略 ...

// 写入Firestore的核心代码
const docRef = await addDoc(collection(db, "AddedRecipes"), {
    // 文档字段省略
});

问题原因

  1. 规则匹配范围错误:当前规则直接匹配根路径/databases/{database}/documents,未针对AddedRecipes集合做精准匹配,导致实际请求时权限判断不对应目标集合。
  2. 规则逻辑无针对性:根路径同时设置全局读写和只读规则,没有绑定到目标集合,权限逻辑混乱,无法满足指定集合的权限需求。

解决方案

修改Firestore规则,精准匹配AddedRecipes集合,明确区分读写权限:

service cloud.firestore {
  match /databases/{database}/documents {
    // 精准匹配AddedRecipes集合下的所有文档
    match /AddedRecipes/{document} {
      // 已登录用户允许读写
      allow read, write: if request.auth != null;
      // 未登录用户仅允许读取
      allow read: if request.auth == null;
    }
  }
}

额外检查项

  • 确认前端写入操作时用户已完成登录:可通过getAuth().currentUser判断用户登录状态,避免未登录时触发写入请求。
  • 验证规则生效:修改规则后等待5-10分钟(Firestore规则生效有延迟),或在Firebase控制台的规则模拟器中测试读写请求,确认权限符合预期。
  • 检查Storage权限:如果同时存在Storage上传报错,需单独配置Firebase Storage规则,确保上传操作的权限正确。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 22:02:36