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

Firebase安全规则验证失败,请求逻辑看似合规

Firestore权限问题排查与解决

问题描述

使用TypeScript开发Web应用时,调用添加预约的接口被Firestore安全规则拒绝,报错:

Uncaught (in promise) FirebaseError: 缺少或权限不足。

相关代码

前端TypeScript代码

export async function setNewAppointment(appointment: Appointment) {
  const user = auth.currentUser;

  await addDoc(collection(db, "appointments"), {
    user_id: "blah",
    id: appointment.id,
    title: appointment.title,
    start_time: Timestamp.fromMillis(appointment.start_time),
    end_time: Timestamp.fromMillis(appointment.end_time),
    description: appointment.description,
    location: appointment.location,
  });
}

Firestore安全规则配置

rules_version = '2';
service cloud.firestore {
    match /databases/{database}/documents {
        match /{document=**} {
            allow read, write: if false;
        }
        match /users/{userId} {
            allow read, write: if request.auth.uid == userId;
        }
        match /appointments/{appointmentId} {
            allow read, write: if "blah" == resource.data.user_id;
        }
    }
}

问题原因与解决方案

核心问题

  1. 规则顺序错误:顶层通配规则match /{document=**}优先级最高,会先拒绝所有读写操作,后续针对appointments的规则根本不会生效。
  2. 字段校验对象错误:添加文档时(write操作中的create场景),resource对象还未存在,无法通过resource.data.user_id读取字段,需改用request.resource.data.user_id获取请求中携带的待写入数据。

修改后的安全规则

rules_version = '2';
service cloud.firestore {
    match /databases/{database}/documents {
        match /users/{userId} {
            allow read, write: if request.auth.uid == userId;
        }
        match /appointments/{appointmentId} {
            allow create: if request.auth != null && request.resource.data.user_id == "blah";
            allow read, update, delete: if request.auth != null && resource.data.user_id == "blah";
        }
        match /{document=**} {
            allow read, write: if false;
        }
    }
}

规则说明

  • 调整顺序:将具体集合的匹配规则放在通配规则之前,确保Firebase优先匹配针对性规则。
  • 区分操作类型:对create操作使用request.resource校验待写入字段,对read/update/delete使用resource校验已存在文档的字段,逻辑更精准。
  • 增加登录校验:request.auth != null确保只有已登录用户能执行操作,避免未授权访问。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 19:15:34