Firebase安全规则修改后谷歌登录用户无法写入数据库求助
问题解决:谷歌登录用户无法写入Firebase数据库
核心原因:你只完成了Google账号的客户端登录,但没有将其关联到Firebase Authentication,导致Firebase后端无法识别用户的认证状态,规则中的request.auth.uid为空,写操作被拒绝。
解决方案
1. 修改登录流程,关联Firebase Auth
首先确保已导入firebase_auth包,然后完善functionToSignin函数,将Google登录凭证同步到Firebase Auth:
import 'package:firebase_auth/firebase_auth.dart'; // ... functionToSignin(GoogleSignInAccount? account) async { if (account != null) { print('got an account from google'); print('User signed in: $account'); // 新增:获取Google登录的认证凭证 final GoogleSignInAuthentication googleAuth = await account.authentication; final AuthCredential credential = GoogleAuthProvider.credential( accessToken: googleAuth.accessToken, idToken: googleAuth.idToken, ); // 用凭证登录Firebase Auth await FirebaseAuth.instance.signInWithCredential(credential); await addUserInFirestore(); setState(() { isAuth = true; }); } else { setState(() { isAuth = false; }); } }
2. 规范数据库操作的用户ID来源
数据库操作时,建议从Firebase Auth获取用户ID(而非GoogleSignIn的ID,两者通常一致,但Firebase Auth的uid是后端认证的标准标识):
final userReference = FirebaseFirestore.instance.collection('users'); // 从Firebase Auth获取当前认证用户 final firebaseUser = FirebaseAuth.instance.currentUser; if (firebaseUser == null) { // 处理未登录逻辑,比如提示用户登录 return; } DocumentSnapshot doc = await userReference.doc(firebaseUser.uid).get(); if (!doc.exists) { await userReference.doc(firebaseUser.uid).set({ "id": firebaseUser.uid, }); doc = await userReference.doc(firebaseUser.uid).get(); }
3. 安全规则无需修改
你的原有规则allow write: if request.auth.uid != null;是正确的,它对所有通过Firebase Auth认证的用户生效(包括邮箱密码、谷歌登录等),完成上述修改后,谷歌登录用户即可正常写入数据库。
内容的提问来源于stack exchange,提问作者ABS CEDAR
相关产品推荐
相关产品推荐

