Firebase创建账号时写入Firestore数据权限问题求助
问题详情
创建用户账号时,尝试将姓名、用户名等数据写入Firestore的Users集合,触发以下权限错误:
W/Firestore( 9927): (24.5.0) [Firestore]: Write failed at Users/FPhBBFybqXfCuXtFYTVO: Status{code=PERMISSION_DENIED, description=Missing or insufficient permissions., cause=null}
I/flutter ( 9927): [cloud_firestore/permission-denied] The caller does not have permission to execute the specified operation.
当前使用的Firestore安全规则:
rules_version = '2'; service cloud.firestore { match /databases/{database}/documents { match /{document=**} { allow create: if request.auth != null; allow read, write, update, delete: if request.auth != null; } } }
问题分析
当前规则要求所有操作必须在用户已认证(request.auth != null)的前提下执行,但出现权限拒绝通常有两种原因:
- 写入操作时用户尚未完成Firebase Auth认证
- 写入的
Users文档ID与当前认证用户的uid不匹配(不过你的错误更偏向第一种情况)
解决方案
方案1:认证后写入自身用户数据(推荐)
这是最安全的做法:用户完成Firebase Auth认证后,仅允许其写入/操作自己的Users文档(文档ID等于用户uid)。修改规则如下:
rules_version = '2'; service cloud.firestore { match /databases/{database}/documents { // 针对Users集合的精准规则 match /Users/{userId} { // 允许创建:用户已认证,且文档ID等于当前用户UID allow create: if request.auth != null && request.auth.uid == userId; // 允许读写更新删除:仅能操作自己的文档 allow read, write, update, delete: if request.auth != null && request.auth.uid == userId; } // 其他集合默认禁止访问,按需修改 match /{document=**} { allow read, write: if false; } } }
使用该规则时,确保代码中:
- 用户先完成Firebase Auth登录/注册流程
- 创建
Users文档时,将文档ID设置为当前用户的uid(示例代码:FirebaseFirestore.instance.collection('Users').doc(user.uid).set(userData))
方案2:认证前写入数据(不推荐,存在安全风险)
如果业务需要在用户完成认证前写入数据(比如先提交注册信息再创建认证账号),可以临时放宽创建权限,但后续仍限制为仅对应UID用户可操作:
rules_version = '2'; service cloud.firestore { match /databases/{database}/documents { match /Users/{userId} { // 允许任何人创建文档 allow create: true; // 后续仅允许对应UID的认证用户操作 allow read, write, update, delete: if request.auth != null && request.auth.uid == userId; } } }
注意:此方案可能被恶意用户滥用,建议尽量通过Firebase云函数处理这类预认证写入,避免直接开放创建权限。
测试验证
可以通过Firebase控制台的规则模拟器测试规则:
- 模拟已认证用户(输入UID),测试写入
Users/[该UID]文档,确认权限通过 - 模拟未认证用户,测试写入操作,确认权限被拒绝(方案1)
内容的提问来源于stack exchange,提问作者Wagner Tiburcio

