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

Firestore安全规则报错:Invalid variable name: request 问题排查

问题原因及解决方法

错误Invalid variable name: request.的核心原因是:Firestore规则v2中,request是请求上下文变量,仅在match块的作用域内可用,你把用到request的isAuthenticated()函数定义在了service层级(所有match块之外),这个层级的函数无法访问request上下文,所以触发变量名无效的错误。

修复方案

将所有依赖request的函数移到match /databases/{database}/documents块内部,确保它们处于能访问请求上下文的作用域中。修改后的规则代码如下:

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    // 移到match块内,现在可以正常访问request
    function isAuthenticated() {
      return request.auth != null;
    }

    function isUserCompanyAdmin(companyID) {
      return isAuthenticated() &&
        request.auth.token.role == 'admin' && request.auth.token.companyID == companyID;
    }

    match /companies/{companyId} {
      allow read, write, update, delete, create, get: if isUserCompanyAdmin(companyId);
    }
  }
}

补充说明

Firestore规则v2对作用域做了严格限制,顶级函数(service层级)只能访问全局常量或无上下文依赖的逻辑,任何需要请求上下文(比如request、resource)的函数必须放在match块内部,这样才能绑定到具体的请求/文档上下文。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 19:54:52