Flutter Firebase - 未能正确删除 Google 认证用户

Flutter Firebase - failing to properly delete a Google authenticated user

我正在尝试,但未能重新触发用户在删除用户后使用 Google 登录验证自己时所执行的验证步骤。当第二次使用 Google 登录时,删除的用户会立即登录(而不是通过身份验证步骤)。为了我自己的测试目的,我希望能够重新触发身份验证步骤。

具体来说,我有一个用户,我已经根据 FlutterFire documentation 进行了身份验证和登录,即

Future<UserCredential> signInWithGoogle() async {
  // Trigger the authentication flow
  final GoogleSignInAccount googleUser = await GoogleSignIn().signIn();

  // Obtain the auth details from the request
  final GoogleSignInAuthentication googleAuth = await googleUser.authentication;

  // Create a new credential
  final GoogleAuthCredential credential = GoogleAuthProvider.credential(
    accessToken: googleAuth.accessToken,
    idToken: googleAuth.idToken,
  );

  // Once signed in, return the UserCredential
  return await FirebaseAuth.instance.signInWithCredential(credential);
}

然后我继续删除用户;同样,根据 FlutterFire documentation,即

try {
  await FirebaseAuth.instance.currentUser.delete();
} catch on FirebaseAuthException (e) {
  if (e.code == 'requires-recent-login') {
    print('The user must reauthenticate before this operation can be executed.');
  }
}

这行得通,因为该用户不再列在 Firebase 控制台的经过身份验证的用户中。 但是,如果我现在再次调用 signInWithGoogle(),那么就不会再次执行身份验证步骤(即被提示输入电子邮件、密码等) .),用户只需立即登录即可。就好像用户没有被正确删除一样。我将如何重新触发身份验证步骤?

您还必须在 Firebase 注销或删除后调用 GoogleSignIn().signOut()

在我的例子中,我不得不在删除函数 try-catch 中重新验证 firebase 用户,因为 currentUser() 总是 return null 并且 GoogleSignIn().signOut() 没有用。可能是一个错误。

 import 'package:google_sign_in/google_sign_in.dart';
 import 'package:firebase_auth/firebase_auth.dart';

 final GoogleSignIn _googleSignIn = GoogleSignIn();
 final FirebaseAuth _auth = FirebaseAuth.instance;

//will need to sign in to firebase auth again as currentUser always returns null
//this try-catch block should be inside the function that deletes user

try {
  //FirebaseUser user = await _auth.currentUser(); //returns null so useless

  //signin to google account again
  GoogleSignInAccount googleSignInAccount = await _googleSignIn.signIn();
  GoogleSignInAuthentication googleSignInAuthentication =
      await googleSignInAccount.authentication;
  //get google credentials
  AuthCredential credential = GoogleAuthProvider.getCredential(
      idToken: googleSignInAuthentication.idToken,
      accessToken: googleSignInAuthentication.accessToken);

  //use credentials to sign in to Firebase
  AuthResult authResult = await _auth.signInWithCredential(credential);
  //get firebase user
  FirebaseUser user = authResult.user;
  print(user.email);
  //delete user
  await user.delete();
  //signout from google sign in
  await _googleSignIn.signOut();
} catch (e) {
  print('Failed to delete user ' + e.toString());
}