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

Firebase如何区分匿名与Google登录用户并配置安全规则?

Firebase安全规则区分匿名登录与Google登录的方法

在Firebase安全规则中,可通过request.auth.provider属性直接识别用户的登录方式:

  • 匿名登录用户的request.auth.provider值为"anonymous"
  • Google登录用户的request.auth.provider值为"google.com"

示例规则配置

以下是针对两类用户设置权限差异的规则示例,比如限制匿名用户仅能读取特定数据、禁止写入;允许Google登录用户拥有完整读写权限:

Cloud Firestore 规则示例

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    // 匿名用户仅可读取公开数据,禁止写入
    match /public_content/{doc} {
      allow read: if request.auth != null && request.auth.provider == "anonymous";
      allow write: if false;
    }

    // Google登录用户允许读写所有数据
    match /{document=**} {
      allow read, write: if request.auth != null && request.auth.provider == "google.com";
    }
  }
}

Realtime Database 规则示例

{
  "rules": {
    // Google登录用户可读写全量数据
    ".read": "auth != null && auth.provider == 'google.com'",
    ".write": "auth != null && auth.provider == 'google.com'",
    // 匿名用户仅可读取公开数据,禁止写入
    "public_data": {
      ".read": "auth != null && auth.provider == 'anonymous'",
      ".write": false
    }
  }
}

注意:配置规则时需先判断request.auth != null(Realtime Database为auth != null),避免未登录用户触发规则时出现报错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 15:02:37