Handling Firebase Authentication Errors and Failures

From Techotopia
Revision as of 14:22, 14 August 2017 by Neil (Talk | contribs)

Jump to: navigation, search

A key part of providing a good user experience involves not just letting users know when something has failed, but also providing a useful explanation as to why the failure occurred. The more information that is provided about a failure, the greater the likelihood that the user will be able to resolve the problem.

In the Firebase authentication examples created in this book so far, very little effort has been made beyond simply notifying the user that a failure occurred. The apps will, for example, let the user know that a login attempt has failed without giving an explanation as to why.

This chapter will introduce the use of Firebase authentication failure listeners in terms of identifying not just that a failure has occurred, but also the nature of the failure.


Contents


Completion Listeners and Basic Failure Detection

User authentication using Firebase primarily consists of obtaining a reference to the FirebaseAuth instance or a FirebaseUser object on which method calls are made to create accounts, sign-in users and perform account management tasks. All of these methods perform the requested task asynchronously. This essentially means that immediately after the method is called, control is returned to the app while the task is performed in the background. As is common with asynchronous tasks of this type, it is possible for the app to be notified that the authentication task has finished by providing a completion listener method to be called when the task completes.

Consider, for example, the following code fragment from the FirebaseAuth project:

fbAuth.signInWithEmailAndPassword(email, password)
        .addOnCompleteListener(this, 
	       new OnCompleteListener<AuthResult>() {
            @Override
            public void onComplete(@NonNull Task<AuthResult> task) {

                if (!task.isSuccessful()) {
                     // Notify user of failure
                }
            }
         });

This code performs an email and password based user sign-in operation involving the use of a completion listener to be called when the task completes. As currently implemented, the only status information available is a success or failure value on the task object of the completion handler method. This allows the app to tell the user the sign-in failed, but does not provide any context as to why. To be able to obtain more information about the reason for the failure, a failure listener needs to be added to the call.

The Failure Listener

In much the same way that a completion handler is called when an asynchronous task completes, a failure handler is called when the task fails to complete due to a problem or error. Failure listeners are added to Firebase authentication method calls via the addOnFailureListener() method. The above code, for example, can be extended to add a failure listener as follows:

fbAuth.signInWithEmailAndPassword(email, password)
        .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
            @Override
            public void onComplete(@NonNull Task<AuthResult> task) {

                if (!task.isSuccessful()) {
			// Notify user of failure
                }
            }
        }).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                
            }
     });   

Open the FirebaseAuth project in Android Studio, load the FirebaseAuthActivity.java file into the editing panel and make the above changes to the signInWithEmail() method.

When using the addOnFailureListener() method within an activity, it will also be necessary to import the Android OnFailureListener package:

import com.google.android.gms.tasks.OnFailureListener;

When a failure occurs during the sign-in process, the onFailure() method will be called and passed an Exception object containing information about the reason for the failure. The exact type of the exception thrown will depend on the nature of the error. An invalid password, for example, will throw a different type of exception than that generated when trying to create an account using an email address that conflicts with an existing account.

The simplest form of the user notification is to simply display the localized description to the user as outlined in the following code fragment:

fbAuth.signInWithEmailAndPassword(email, password)
        .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
            @Override
            public void onComplete(@NonNull Task<AuthResult> task) {

                if (!task.isSuccessful()) {
			// Notify user of failure
                }
            }
        }).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                notifyUser(e.getLocalizedMessage());
            }
     });

Note that when using a failure listener it is no longer necessary to check for failure within the completion listener method. Doing so will likely result in duplicated app behavior. Make this change to the signInWithEmailAndPassword() method and build, run and test the new behavior in the app.

If an attempt is now made to sign in using an email address for which no account yet exists, the above code displays a message which reads as follows:

There is no user record corresponding to this identifier. The user may have been deleted.

If, on the other hand, a correct email address is used with an incorrect password, the localized description string will read as follows:

The password is invalid or the user does not have a password.

While useful as a quick way to notify the user of the nature of the problem, it is quite likely that greater control over how the failure is reported and what actions are taken next will often be required. This involves identifying the type of the Exception object and accessing the error code.


FirebaseAuth Exception Types

The type of exception thrown by the Firebase SDK in the event of an authentication failure can be used to identify more information about the cause of the failure. In the previous section, the built-in failure description was presented to the user, but the app itself made no attempt to identify the cause of the failure. While this may be acceptable for many situations, it is just as likely that the app will need more information about what went wrong.

In the event of an authentication failure, the Firebase SDK will throw one the following types of exception:

FirebaseAuthInvalidUserException – This exception indicates a problem with the email address entered by the user. For example, the account does not exist or has been disabled in the Firebase console. The precise reason for the exception can be identified by accessing the error code as outlined later in this chapter.

FirebaseAuthInvalidCredentialsException – This exception is thrown when the password entered by the user does not match the email address.

FirebaseAuthUserCollisionException – Thrown during account creation, this exception indicates a problem with the email address entered by the user. The exact reason for the failure can be identified by accessing the error code.

FirebaseAuthWeakPasswordException – Indicates that the password specified during an account creation or password update operation is insufficiently strong. A string describing the reason that the password is considered too weak can be obtain via a call to the getReason() method of the exception object.

FirebaseAuthRecentLoginRequiredException – The user has attempted to perform a security sensitive operation but too much time has elapsed since signing in to the app. When this exception is detected the user will need to be re-authenticated as outlined later in this chapter.

With knowledge of the different exception types, the previous sample code can be modified to identify if the sign-in failure was due to an issue with the email or password entry. This can be achieved by finding out the type of the Exception object. To see this in action, modify the onFailure() method located in the signInWithEmail() method so that it reads as follows:

.
.
@override
public void onFailure(@NonNull Exception e) {
    if (e instanceof FirebaseAuthInvalidCredentialsException) {
        notifyUser("Invalid password");
    } else if (e instanceof FirebaseAuthInvalidUserException) {
        notifyUser("Incorrect email address");
    } else {
	notifyUser(e.getLocalizedDescription());
    }
}
.
.

Compile and run the app once again and try signing in with invalid email and password combinations. The error notifications displayed by the app will now differentiate between an email address problem and an invalid password. The code also makes use of the localized description string contained within the exception to catch instances that do not match the credential and user exceptions.

Although this is an improvement on the original code, it would be helpful to provide yet more detail. The code, for example, does not provide any information about why email address was found to be incorrect. Adding this level of information involves the use of the exception error codes.

FirebaseAuth Error Codes =

In addition to identifying the cause of a failure by finding the type of the exception, additional information can be obtained by inspecting the error code contained within the exception object. Error codes are currently available for the invalid user and user collision exceptions.

The error codes supported by FirebaseAuthInvalidUserException are as follows:

ERROR_USER_DISABLED – The account with which the email is associated exists but has been disabled.

ERROR_USER_NOT_FOUND – No account could be found that matches the specified email address. The user has either entered the wrong email address, has yet to create an account or the account has been deleted.

ERROR_USER_TOKEN_EXPIRED – The user’s token has been invalidated by the Firebase system. This usually occurs when the user changes the password associated with the account from another device or platform (such as a web site associated with the app).

ERROR_INVALID_USER_TOKEN – The system does not recognize the user’s token as being correctly formed. FirebaseAuthUserCollisionException, on the other hand, supports the following error codes:

ERROR_EMAIL_ALREADY_IN_USE – Indicates that the user is attempting to create a new account, or change the email address for an existing account that is already in use by another account. • ERROR_ACCOUNT_EXISTS_WITH_DIFFERENT_CREDENTIAL – When attempting to sign in to an account using the signInWithCredential() method passing through an AuthCredential object, this error indicates that the email associated with the AuthCredential instance is already in use by another account that does not match the provided credentials.

ERROR_CREDENTIAL_ALREADY_IN_USE – It is quite possible for one user to establish multiple accounts by using different authentication providers. As will be outlined in Linking and Unlinking Firebase Authentication Providers, Firebase provides the ability for these separate accounts to be consolidated together through a process of account linking. This error indicates that an attempt has been made to link a credential to an account that is already linked to another account.

These error codes are provided in the form of string objects containing the error code name. Testing for an error, therefore, simply involves performing string comparisons against the error code.

By using error codes, the previous code to identify an invalid user exception within the onFailure() method can be improved to identify the exact cause of the failure simply by accessing the error code in the exception object. For example:

@Override
public void onFailure(@NonNull Exception e) {
    if (e instanceof FirebaseAuthInvalidCredentialsException) {
        notifyUser("Invalid password");
    } else if (e instanceof FirebaseAuthInvalidUserException) {

        String errorCode = 
		((FirebaseAuthInvalidUserException) e).getErrorCode();

        if (errorCode.equals("ERROR_USER_NOT_FOUND")) {
            notifyUser("No matching account found");
        } else if (errorCode.equals("ERROR_USER_DISABLED")) {
            notifyUser("User account has been disabled");
        } else {
            notifyUser(e.getLocalizedMessage());
        }
    }
}

With these changes implemented, compile and run the app and try to sign in with an unregistered email address. The app should respond with the message indicating that no matching account could be found.

Next, open the Firebase console in a browser window and navigate to the Users screen of the Authentication section for the Firebase Examples project. Using the menu to the right of one of the existing user account entries, select the Disable Account menu option as outlined in Figure 12-1:


Firebase auth disable account.png

Figure 12-1


With the account disabled, return to the app and attempt to sign in using the email address assigned to the disabled account. This time the app will display the account disabled error message.

Handling Secure Action Exceptions

Now that the basics of authentication exception handling have been covered, it is time to return to the subject of secure actions. The topic of secure actions was introduced in the chapter entitled Managing User Accounts using the Firebase SDK. In summary, secure actions are a category of account management operation that may only be performed if the current user recently signed in. Such operations include changing the user’s password or email address via calls to the Firebase SDK. If the user recently signed into the app, these operations will complete without any problems. If it has been a few hours since the current user signed in, however, the operation will fail with a FirebaseAuthRecentLoginRequiredException exception.

Consider, for example, the code that allows a user to update the account password:

FirebaseUser user = fbAuth.getCurrentUser();

user.updatePassword(newPassword)
        .addOnCompleteListener(new OnCompleteListener<Void>() {
            @Override
            public void onComplete(@NonNull Task<Void> task) {
                if (task.isSuccessful()) {
                    notifyUser("Password updated");
                }
            }
        });

Clearly, given the fact that this is categorized as a secure action, some code needs to be added to identify when the recent login required exception is thrown. This, once again, involves the use of a failure listener to check for the type of exception:

user.updatePassword(newPassword)
        .addOnCompleteListener(new OnCompleteListener<Void>() {
            @Override
            public void onComplete(@NonNull Task<Void> task) {
                if (task.isSuccessful()) {
                    notifyUser("Password updated");
                }
            }
        }).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                if (e instanceof FirebaseAuthRecentLoginRequiredException) {
                    notifyUser("Re-authentication needed");
                }
        }
    });

As implemented above, when the user attempts to perform a password update after having been signed in for too long, the exception will be caught and the user notified of the problem. One less than optimal solution to this problem would be to instruct the user to sign out, sign back in again and perform the password update a second time. A far more user friendly approach, however, is to re-authenticate the user.

The first step in the re-authentication process involves obtaining the current user’s credentials in the form of an AuthCredential object. This is achieved by passing the user’s email and password through to the getCredential() method of the appropriate authentication provider which, depending on the form of authentication, will be one of the following:

• EmailAuthProvider

• GoogleAuthProvider

• FacebookAuthProvider

• TwitterAuthProvider

• GitHubAuthProvider

When obtaining the user’s credentials during the re-authentication for a password update action, it is important to be aware that it is the user’s current password that must be used, not the new password to which the user is attempting to change. If the app has not stored the existing password internally, the user will need to be prompted to enter it before the credentials can be obtained and the account re-authenticated. The following code obtains the AuthCredential object using the email authentication provider:

AuthCredential credential = EmailAuthProvider
        .getCredential(email, currentPassword); 

Once the updated credentials have been obtained, the re-authentication is ready to be performed by making a call to the reauthenticate() method of the current user’s FirebaseUser instance, passing through the AuthCredential object as an argument:

final FirebaseUser user = fbAuth.getCurrentUser();

user.updatePassword(newPassword)
        .addOnCompleteListener(new OnCompleteListener<Void>() {
            @Override
            public void onComplete(@NonNull Task<Void> task) {
            }
        }).addOnFailureListener(new OnFailureListener() {

    @Override
    public void onFailure(@NonNull Exception e) {
        if (e instanceof FirebaseAuthRecentLoginRequiredException) {
            AuthCredential credential = EmailAuthProvider
                    .getCredential(email, currentPassword);

            user.reauthenticate(credential)
                .addOnCompleteListener(new OnCompleteListener<Void>() {
                    @Override
                    public void onComplete(@NonNull Task<Void> task) {
			// Re-authentication was successful
			// Re-attempt secure password update action
                    }
                }).addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {
                        notifyUser(e.getLocalizedMessage());
                    }
            });
        }
    }
}); 

As implemented, the code obtains the user’s credentials and initiates the re-authentication. A completion listener is added to the operation where appropriate code can be added to re-attempt the secure action (in this case a password update). A failure listener is also added to the re-authentication method call and used to display the localized error description from any exception that is thrown during the re-authentication procedure.

Summary

There are few issues more annoying to a user than problems encountered when creating an account for, or signing in to an app. While it is impossible to eliminate all potential errors during the user authentication process, providing useful and informative feedback on the nature of any problems goes a long way toward alleviating the user’s frustration. In order to provide information about the problem it is first necessary to be able to identify the cause. As outlined in this chapter, this can be achieved by adding failure listeners when making calls to Firebase SDK methods. When called, these failure listeners will be passed an exception object. By identifying the type of the exception and accessing error codes and description strings, an app can provide detailed information to the user on the cause of an authentication failure.

As also demonstrated in this chapter, the ability to identify recent login required exceptions when performing secure actions is a key requirement when a user needs to be re-authenticated.