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

按官方文档配置Firestore规则仍权限不足,Flutter本地模拟器问题

解决Firestore创建用户文档权限拒绝问题

问题分析

你遇到的PERMISSION_DENIED错误,核心原因是依赖FirebaseAuth.instance.currentUser获取UID时存在本地状态同步延迟。虽然createUserWithEmailAndPassword已成功创建用户,但Auth的本地currentUser状态可能还未及时更新,导致Firestore规则校验时出现异常。

解决方案

直接使用createUserWithEmailAndPassword返回的UserCredential中的用户对象获取UID,避免依赖延迟的currentUser状态:

修改后的代码:

UserCredential userCredential = await auth
          .createUserWithEmailAndPassword(email: data.name!, password: data.password!);
await userCredential.user!.sendEmailVerification(); // 改用刚创建的用户对象发送验证邮件
DocumentReference ref = FirebaseFirestore.instance.collection("users").doc(userCredential.user!.uid);
await ref.set({"isOwner":false},SetOptions(merge: true));

额外检查点

  • 确保Flutter项目中Auth和Firestore模拟器配置一致,两者使用同一项目ID以保证认证上下文互通:
    // 模拟器初始化示例
    FirebaseAuth.instance.useAuthEmulator('localhost', 9099);
    FirebaseFirestore.instance.useFirestoreEmulator('localhost', 8080);
    
  • 确认Firestore规则逻辑无问题,你当前的规则是合法的:
    rules_version = '2';
    service cloud.firestore {
      match /databases/{database}/documents {
        match /users/{userId} {
              allow read, update, delete: if request.auth != null && request.auth.uid == userId;
              allow create: if request.auth != null;
            }
      }
    }
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 11:10:12