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

配置Firestore生产模式安全规则后所有PHP编写的查询无法执行如何解决

问题原因
  • 安全规则逻辑错误:你定义的isLoggedIn()函数中,"{someuserID}"是固定字符串字面量,并非动态获取路径参数的变量,同时函数未接收路径中匹配到的someuserID参数,导致规则验证永远返回false,所有请求都被拦截。
  • 查询逻辑与规则约束不匹配:Firestore安全规则不是过滤器,不会自动对查询结果做过滤。你当前的PHP代码是查询contacts全集合的前2条文档,但规则要求仅当文档ID等于登录用户UID时才可访问,规则无法验证这个全集合查询返回的所有文档都符合约束,因此直接拒绝查询。
修复方案

根据你的业务场景选择对应方案:

场景1:contacts集合下每个文档对应一个用户(文档ID=用户UID,单用户仅1个对应文档)

1. 修正安全规则

match /databases/{database}/documents {
  match /contacts/{someuserID} {
    allow read, create, update, delete: if isLoggedIn(someuserID);
  }
}
  
function isLoggedIn(targetUid) {
    // 先判断用户已登录,再校验UID匹配
    return request.auth != null && request.auth.uid == targetUid;
}

2. 修正PHP查询代码

需要明确指定查询的文档ID为当前登录用户的UID,不能查询全集合:

<?php
// $currentUid 替换为你通过Firebase Auth获取到的当前登录用户的实际UID
$currentUid = '当前登录用户的UID';
$userDoc = $db->collection('contacts')->document($currentUid)->snapshot();
?>

场景2:contacts集合下存储所有联系人文档,每个用户仅可访问自己创建的联系人

1. 先给contacts集合的所有文档新增owner字段,值为创建该联系人的用户UID

2. 修正安全规则

match /databases/{database}/documents {
  match /contacts/{contactID} {
    allow read, create, update, delete: if request.auth != null && request.auth.uid == resource.data.owner;
  }
}

3. 修正PHP查询代码

查询时增加owner字段的过滤条件,匹配规则约束:

<?php
$currentUid = '当前登录用户的UID';
$getdata = $db->collection('contacts')
  ->where('owner', '=', $currentUid)
  ->orderBy('createdAt', 'desc')
  ->limit(2)
  ->documents();
?>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 11:30:02