如何从 Android 应用程序中删除 Firebase 用户?

How to delete a Firebase user from Android App?

我正在尝试在我的 Android 应用程序中编写 Delete User 方法,但每次执行它时都会遇到一些问题。当用户在 Activity 上按下 删除帐户 按钮时,将执行此方法。我的应用程序适用于 FirebaseUI Auth。

方法如下:

private void deleteAccount() {
    Log.d(TAG, "ingreso a deleteAccount");
    FirebaseAuth firebaseAuth = FirebaseAuth.getInstance();
    final FirebaseUser currentUser = firebaseAuth.getCurrentUser();

    currentUser.delete().addOnCompleteListener(new OnCompleteListener<Void>() {
        @Override
        public void onComplete(@NonNull Task<Void> task) {
            if (task.isSuccessful()) {
                Log.d(TAG,"OK! Works fine!");
                startActivity(new Intent(Main3WelcomeActivity.this, Main3Activity.class));
                finish();
            } 
        }
    }).addOnFailureListener(new OnFailureListener() {
        @Override
        public void onFailure(@NonNull Exception e) {
            Log.e(TAG,"Ocurrio un error durante la eliminación del usuario", e);
        }
    });
}

1) 当我执行该功能时,屏幕上会出现一条 Smart Lock 消息,用户会再次登录。这是此消息的屏幕截图。

2) 其他场合,当用户长时间登录时,函数会抛出这样的Exception:

06-30 00:01:26.672 11152-11152/com.devpicon.android.firebasesamples E/Main3WelcomeActivity: Ocurrio un error durante la eliminación del usuario
com.google.firebase.FirebaseException: An internal error has occured. [ CREDENTIAL_TOO_OLD_LOGIN_AGAIN ]
at com.google.android.gms.internal.zzacq.zzbN(Unknown Source)
at com.google.android.gms.internal.zzacn$zzg.zza(Unknown Source)
at com.google.android.gms.internal.zzacy.zzbO(Unknown Source)
at com.google.android.gms.internal.zzacy$zza.onFailure(Unknown Source)
at com.google.android.gms.internal.zzact$zza.onTransact(Unknown Source)
at android.os.Binder.execTransact(Binder.java:453)

我读过 I have to re-authenticate 用户,但我不确定在使用 Google 登录时如何执行此操作。

使用这个方法:-

删除()

相当于调用set(null)

removeUser()

removeUser(credentials, [onComplete])

根据 Firebase 文档,用户可以使用 delete() 方法从 Firebase

中删除用户

删除用户前请重新验证用户。

Sample code

     final FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();

        // Get auth credentials from the user for re-authentication. The example below shows
        // email and password credentials but there are multiple possible providers,
        // such as GoogleAuthProvider or FacebookAuthProvider.
        AuthCredential credential = EmailAuthProvider
                .getCredential("user@example.com", "password1234");

        // Prompt the user to re-provide their sign-in credentials
        user.reauthenticate(credential)
                .addOnCompleteListener(new OnCompleteListener<Void>() {
                    @Override
                    public void onComplete(@NonNull Task<Void> task) {
           user.delete()
            .addOnCompleteListener(new OnCompleteListener<Void>() {
                @Override
                public void onComplete(@NonNull Task<Void> task) {
                    if (task.isSuccessful()) {
                        Log.d(TAG, "User account deleted.");
                    }
                }
            });

   }
});

更多详情:https://firebase.google.com/docs/auth/android/manage-users#re-authenticate_a_user

如果要用户重新认证其他singin provider只需要将Provider改成GoogleAuthProvider 下面是示例代码

GoogleAuthProvider.getCredential(googleIdToken,null);

您的 delete 回调已经处理了失败的情况,为什么您稍后添加 addOnFailureListener

尝试删除它,这样:

private void deleteAccount() {
    Log.d(TAG, "ingreso a deleteAccount");
    FirebaseAuth firebaseAuth = FirebaseAuth.getInstance();
    final FirebaseUser currentUser = firebaseAuth.getCurrentUser();
    currentUser.delete().addOnCompleteListener(new OnCompleteListener<Void>() {
        @Override
        public void onComplete(@NonNull Task<Void> task) {
            if (task.isSuccessful()) {
                Log.d(TAG,"OK! Works fine!");
                startActivity(new Intent(Main3WelcomeActivity.this, Main3Activity.class));
                finish();
            } else {
                Log.w(TAG,"Something is wrong!");
            }
        }
    });
}

首先,您需要在用户登录时存储授权令牌或密码。如果您的应用不提供 Google Sign-in,Facebook Sign-in 或其他,您只需要存储密码即可。

//If there's any, delete all stored content from this user on Real Time Database. 
yourDatabaseReferenceNode.removeValue();

//Getting the user instance.
final FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();

if (user != null) {
    //You need to get here the token you saved at logging-in time.
    String token = "userSavedToken";
    //You need to get here the password you saved at logging-in time.
    String password = "userSavedPassword";

    AuthCredential credential;

    //This means you didn't have the token because user used like Facebook Sign-in method.
    if (token == null) {
       credential = EmailAuthProvider.getCredential(user.getEmail(), password);
    } else {
       //Doesn't matter if it was Facebook Sign-in or others. It will always work using GoogleAuthProvider for whatever the provider.
       credential = GoogleAuthProvider.getCredential(token, null);
    }

    //We have to reauthenticate user because we don't know how long 
    //it was the sign-in. Calling reauthenticate, will update the 
    //user login and prevent FirebaseException (CREDENTIAL_TOO_OLD_LOGIN_AGAIN) on user.delete()
    user.reauthenticate(credential)
            .addOnCompleteListener(new OnCompleteListener<Void>() {
                    @Override
                    public void onComplete(@NonNull Task<Void> task) {
                        //Calling delete to remove the user and wait for a result.
                        user.delete().addOnCompleteListener(new OnCompleteListener<Void>() {
                            @Override
                            public void onComplete(@NonNull Task<Void> task) {
                                if (task.isSuccessful()) {
                                    //Ok, user remove
                                } else {
                                    //Handle the exception
                                    task.getException();
                                }
                            }
                        });
                    }
                });    
}        

Ansuita Jr. 提供的答案解释得非常漂亮并且正确,只有一个小问题。 即使没有重新认证成功,用户也会被删除。 这是因为我们使用

user.delete()

在始终执行的onComplete()方法中。 因此,我们需要添加一个if检查来检查任务是否成功,如下所述

user.reauthenticate(credential)
          .addOnCompleteListener(new OnCompleteListener<Void>() {
             @Override
             public void onComplete(@NonNull Task<Void> task) {
                 if (task.isSuccessful()) {
                    Log.e("TAG", "onComplete: authentication complete");
                    user.delete()
                    .addOnCompleteListener (new OnCompleteListener<Void>() {
                           @Override
                           public void onComplete(@NonNull Task<Void> task) {
                                if (task.isSuccessful()) {
                                    Log.e("TAG", "User account deleted.");
                                } else {
                                    Log.e("TAG", "User account deletion unsucessful.");
                                }
                          }
                     });
                 } else {
                     Toast.makeText(UserProfileActivity.this, "Authentication failed", 
                               Toast.LENGTH_SHORT).show();
                 }
              }
         });

@Android 开发者:

我遇到了一个问题,即 Firebase 身份验证信息在卸载应用程序后仍保留在设备的磁盘中。经过试验和阅读,我发现在 Manifest 的 <application> 标签中设置 android:allowBackup="false"android:fullBackupContent="false" 将确保身份信息在应用程序卸载后不被保留。

请注意,并非所有 Android 设备都存在这种持久性。事实上,它开始出现在我的一台从未有过这个问题的设备上。

只获取当前用户并使用以下方法删除它就可以了

user.delete();

您还可以添加 Oncompletelistner 通过 addinduser.delete().addOnCompleteListner(new OnCompleteListner)以及更多

如果您使用 A​​uthUIFirebaseAuth,您只需执行以下操作

 AuthUI.getInstance().delete(context).addOnSuccessListener {
           
 }.addOnFailureListener{

 }

FirebaseAuth.getInstance().currentUser.delete().addOnSuccessListener...

如果登录方式为“匿名”,您可以调用

FirebaseAuth.getInstance().getCurrentUser().delete().addOnCompleteListener(task -> {
                       if (task.isSuccessful()){
                           Log.d(TAG, "Deletion Success");
                       }
                    });

但如果是其他方式,则需要重新认证。 How to re-authenticate