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

求助:如何为类似亚马逊的电商应用编辑适配Firebase安全规则

电商类Firebase Firestore安全规则适配方案

以下规则针对类亚马逊电商场景的常见数据结构设计,覆盖用户、商品、订单、购物车四类核心业务集合,可直接替换现有规则后根据自身业务字段调整:

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    // 全局默认规则:拒绝所有未显式授权的请求,避免权限溢出
    match /{document=**} {
      allow read, write: if false;
    }

    // 1. 用户信息集合:存储用户收货地址、账户信息等敏感数据
    match /users/{uid} {
      // 仅用户本人可读写自己的个人信息
      allow read, write: if request.auth != null && request.auth.uid == uid;
      // 管理员可读取所有用户信息
      allow read: if request.auth != null && request.auth.token.isAdmin == true;
    }

    // 2. 商品信息集合:存储公开的商品详情、库存、价格数据
    match /products/{productId} {
      // 所有用户(含游客)均可读取商品信息
      allow read: if true;
      // 仅管理员可增删改商品数据
      allow create, update, delete: if request.auth != null && request.auth.token.isAdmin == true;
    }

    // 3. 订单集合:存储用户下单记录、支付状态、物流信息
    match /orders/{orderId} {
      // 仅下单用户可查看、创建自己的订单
      allow read, create: if request.auth != null && request.auth.uid == resource.data.userId;
      // 管理员可查看所有订单、修改订单状态
      allow read, update: if request.auth != null && request.auth.token.isAdmin == true;
    }

    // 4. 购物车集合:存储用户未下单的预选商品
    match /carts/{uid} {
      // 仅用户本人可读写自己的购物车数据
      allow read, write: if request.auth != null && request.auth.uid == uid;
    }
  }
}

额外安全加固要求

  • 写入操作新增字段校验逻辑,避免恶意构造非法数据,例如下单时校验下单用户ID、订单金额、商品列表合法性:
    match /orders/{orderId} {
      allow create: if request.auth != null 
        && request.resource.data.userId == request.auth.uid
        && request.resource.data.amount > 0
        && request.resource.data.products is list;
    }
    
  • 严禁使用测试阶段的全开放规则allow read, write: if true上线
  • 支付密码、银行卡号等敏感支付信息不要存储在Firestore中,对接第三方支付服务完成支付流程
  • 管理员身份通过Firebase自定义声明isAdmin标记,不要在用户文档中存储管理员身份字段避免被篡改

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 03:24:03