How to handle FirebaseAuthUserCollisionException

Viewed 3869

I started getting a FirebaseAuthUserCollisionException exception when I try to sign in with Facebook in my Android application.

com.google.firebase.auth.FirebaseAuthUserCollisionException: An account already exists with the same email address but different sign-in credentials. Sign in using a provider associated with this email address.

I am using Firebase to handle the registration and Facebook to deliver a "one-click" login method, using a com.facebook.login.widget.LoginButton view as a trigger.

These sign-in method was already working. I was able to register a account with Facebook, and use the same method to log-in this account. But now have start to throwing this exception.

Here is the code where I register a account from Facebook and proceed with login:

private void handleFacebookAccessToken(AccessToken token) {
    final ProgressDialog dialog = new ProgressDialog(this);
    dialog.show(getString(R.string.dialog_wait));
    firebaseAuth.signInWithCredential(FacebookAuthProvider.getCredential(token.getToken()))
            .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                @SuppressWarnings("ThrowableResultOfMethodCallIgnored")
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {
                    if (task.isSuccessful()) {
                        dialog.close();
                        registerNewUserFromSocialLogin(firebaseAuth.getCurrentUser());
                    } else {
                        if(task.getException() instanceof FirebaseAuthUserCollisionException) {

                            //TODO: handle sign-in with different credentials

                        } else {
                            dialog.close();
                            LoginManager.getInstance().logOut();
                            Toast.makeText(LoginActivity.this,
                                    R.string.error_login,
                                    Toast.LENGTH_SHORT).show();
                        }
                    }
                }
            });
}

And my Gradle file with current use library:

compile 'com.google.firebase:firebase-auth:10.2.1'
compile 'com.facebook.android:facebook-android-sdk:[4,5)'

So my problem is: I don't know how to handle FirebaseAuthUserCollisionException exception.

None of the solutions in StackOverflow or Firebase Documentation help me. I am looking for a solution that is able to login the user although the duplicated credential, to stil deliver the "one-click" login method.

2 Answers

You will get that error when the user had previously signed in with the same email using a different provider. For example, the user signs in with email user@gmail.com using Google. The user then tries to sign in with the same email but using Facebook. The Firebase Auth backend will return that error (account exists with different credential). In that case, you should use the fetchProvidersForEmail to look up the existing providers associated with email user@gmail.com, in this case google.com. You signInWithCredential to the existing google account to prove ownership of that account, and then linkWithCredential the Facebook credential the user originally was trying to sign in with. This merges both accounts so in the future the user can sign in with either.

This happens when you use the single accounts per email. If you want to allow different accounts per email, you can switch to multiple accounts per email in the Firebase console.

Here is an example:

mAuth.signInWithCredential(authCredential)
    .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
        @Override
        public void onComplete(@NonNull Task<AuthResult> task) {
            // Account exists with different credential. Assume the developer wants to
            // continue and link new credential to existing account.
            if (!task.isSuccessful() &&
                task.getException() instanceof FirebaseAuthUserCollisionException) {
                FirebaseAuthUserCollisionException exception =
                        (FirebaseAuthUserCollisionException)task.getException();
                if (exception.getErrorCode() == 
                    ERROR_ACCOUNT_EXISTS_WITH_DIFFERENT_CREDENTIAL) {
                    // Lookup existing account’s provider ID.
                    mAuth.fetchProvidersForEmail(existingAcctEmail)
                       .addOnCompleteListener(new OnCompleteListener<ProviderQueryResult> {
                          @Override
                          public void onComplete(@NonNull Task<ProviderQueryResult> task) {
                            if (task.isSuccessful()) {
                              if (task.getResult().getProviders().contains(
                                      EmailAuthProvider.PROVIDER_ID)) {
                                // Password account already exists with the same email.
                                // Ask user to provide password associated with that account.
                                ... 
                                // Sign in with email and the provided password.
                                // If this was a Google account, call signInWithCredential instead.
                                mAuth.signInWithEmailAndPassword(existingAcctEmail, password)
                                  addOnCompleteListener(new OnCompleteListener<AuthResult> {
                                    @Override
                                    public void onComplete(@NonNull Task<AuthResult> task) {
                                      if (task.isSuccessful()) { 
                                        // Link initial credential to existing account.
                                        mAuth.getCurrentUser().linkWithCredential(authCredential);
                                      }
                                    }
                                  });
                              }
                            }
                          }
                        });
            }
        }
    });

There is no need for this, you can just allow multiple accounts merge under firebaase->authentication-> sign in method -> Advanced - > change (multiple accounts per email address.

Firebase will merge the same email address but will give you different user UID.

See sample below.

AuthCredential authCredential =  FacebookAuthProvider.getCredential(token.getToken());
    
    mAuth.signInWithCredential(authCredential)
            .addOnCompleteListener(this, task -> {
                if (task.isSuccessful()) {
                    // Sign in success, update UI with the signed-in user's information
                    Log.d(TAG, "signInWithCredential:success");
                    FirebaseUser user = mAuth.getCurrentUser();
                    LoginFacebookGoogleActivity.this.updateUI(user);
                } else {
                    // If sign in fails, display a message to the user.
                    Log.w(TAG, "signInWithCredential:failure", task.getException());

                    if(task.getException() instanceof FirebaseAuthUserCollisionException){
                        FirebaseAuthUserCollisionException exception = (FirebaseAuthUserCollisionException) task.getException();

                        //log this bundle into the analytics to analyze which details you want to collect
                        
                    }

                    Toast.makeText(LoginFacebookGoogleActivity.this, "Authentication failed " + task.getException(), Toast.LENGTH_SHORT).show();
                    LoginFacebookGoogleActivity.this.updateUI(null);
                }
            });
Related