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

Firebase Firestore安全规则配置:仅查看自有发布内容问题

解决方案:Firebase Firestore规则配置及Flutter代码修正

核心问题分析

权限拒绝错误源于两个关键问题:

  • Flutter代码查询的集合错误(当前查询用户UID命名的集合,而非需求中的story集合)
  • 规则配置存在路径语法错误、字段匹配错误,且未与查询条件联动

步骤1:修正Flutter查询代码

需查询story集合并添加uid过滤条件,确保仅获取当前用户发布的内容:

Widget build(BuildContext context) {
    final currentUid = _auth.currentUser?.uid;
    if (currentUid == null) {
      return const Center(child: Text('请先登录'));
    }

    return StreamBuilder(
      stream: FirebaseFirestore.instance
          .collection('story') // 修正为目标集合名
          .where('uid', isEqualTo: currentUid) // 添加UID过滤,与规则联动
          .orderBy('time', descending: true)
          .snapshots(),
      builder: (context, snapshot) {
        if (snapshot.connectionState == ConnectionState.waiting) {
          return const Center(child: CircularProgressIndicator());
        }

        if (snapshot.hasError) {
          return Center(child: Text('加载失败: ${snapshot.error}'));
        }

        if (!snapshot.hasData || snapshot.data!.docs.isEmpty) {
          return const Center(child: Text('暂无发布内容'));
        }

        final feedDocs = snapshot.data!.docs;
        return ListView.builder(
          itemCount: feedDocs.length,
          itemBuilder: (context, index) => Column(
            // 你的列表项UI逻辑
          ),
        );
      },
    );
}

步骤2:正确的Firestore规则配置

以下规则完全匹配你的需求:

  • 已登录用户可写入story集合,且写入文档的uid必须与当前用户UID一致(防止伪造内容)
  • 仅允许用户读取自己发布的内容(通过文档内uid字段匹配)
rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /story/{storyId} {
      // 读取权限:已登录 + 文档uid匹配当前用户uid
      allow read: if request.auth != null && request.auth.uid == resource.data.uid;
      // 写入权限:已登录 + 提交的文档uid匹配当前用户uid
      allow create, update: if request.auth != null && request.auth.uid == request.resource.data.uid;
      // 删除权限:仅允许作者删除自己的文档
      allow delete: if request.auth != null && request.auth.uid == resource.data.uid;
    }
  }
}

原规则失败原因

  1. 路径语法错误:规则中/story /{storyId}包含空格,Firestore路径不允许空格,需改为/story/{storyId}
  2. 字段匹配错误:规则错误使用storyId字段,而你的文档实际存储的是uid字段
  3. 查询未联动规则:Firestore要求查询必须显式过滤出符合权限的结果(即添加where('uid', isEqualTo: currentUid)),否则会直接拒绝整个查询——因为无法确保所有返回结果都满足权限要求

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 01:55:34