Android Firebase Authentication SDK— Email and Password Login

Myrick Chow
ITNEXT
Published in
8 min readFeb 15, 2020

--

Firebase is a great and powerful platform which provides lots of features including Cloud Messaging, Cloud Functions and Cloud Firestore, etc. One of the useful features is Firebase Authentication. It allows developer to directly create and manage user accounts without caring about the underlying server codes! Logged in user can has a token to access secured data in Firestore according to the Firestore security rules.

Firebase provides plenty of authentication methods, including Email/ Password, Google Sign-In, Facebook Sign-In and Sign in with Apple, etc. In this article, we will go through the details and pitfalls of Email/ Password Authentication. Here is the content list:

  1. Prerequisites (4 steps)
  2. Sign-up
  3. Sign-in
  4. Logout
  5. Forget / Reset password
  6. Update password
  7. Update email
  8. Delete user account
  9. Setup email template for resetting password
  10. Limitation

Prerequisites (4 steps):

  1. Create a project with an Android app at Firebase Console, and link Firebase project to your Android app with the use of google-services.json , which is a file generated during your app registration and containing important information, e.g. project_id , package_name and api_key .
google-services.json must be placed at the current module (app) folder.

2. Setup at project build.gradle file

3. Set up at module app.gradle file

Please refer to the Firebase Android Release Notes for the latest version of Firebase Authentication SDK,. It was 19.2.0 at the time of writing this article.

4. Enable Email/Password feature at Firebase Console:

Steps for enabling Email/ Password feature

Feature 1) Sign up

Signing up a new account is as easy as just calling a single function createUserWithEmailAndPassword(email: String, password: String). OnCompleteListener is fired when there is a response returning from Firebase Console no matter the account creation succeeds or not.

OnSuccessListener is fired when account is created successfully. New user’s information can be retrieved by the code FirebaseAuth.getInstance().currentUser. User is automatically logged in after the account is created. No need to call sign-in function!

OnFailureListener is fired when console rejects the account creation. The followings are the possible cases:

  1. FirebaseAuthExceptionEmail/Password sign-in provider is disabled; Developer should enable it back at the Firebase Console. See the 4th point of the above Prerequisites session.
  2. FirebaseAuthUserCollisionException — The email address is already in use by another account
  3. FirebaseAuthInvalidCredentialsExceptionThe email address is badly formatted, e.g. example@!?!?.com
  4. FirebaseAuthWeakPasswordException — The given password is invalid. [ Password should be at least 6 characters ]

Therefore, it is wise to have an email format checking before calling signInWithEmailAndPassword function.

Feature 2) Sign in

By calling signInWithEmailAndPassword(email: String, password: String) , user can sign in easily. There are also 3 callbacks (OnCompleteListener, OnSuccessListener and OnFailureListener) for the sign-in function and user information is ready at the OnSucessListener .

Here are some of the possible exceptions throw into OnFailureListener :

  1. FirebaseAuthInvalidCredentialsException: The password is invalid or the user does not have a password. No matched email account or password.
  2. FirebaseAuthInvalidUserException — The user account has been disabled by an administrator.

* Note that user can login another account without logging out the current account. To prevent accidental overridden of existing user information, developer should manually check the user status before showing the login page.

Feature 3) Sign out current user

Sign-out is not the same as the sign-in and sign-up functions which can be added with callbacks. It only clears the current user information and token locally and therefore it is not an asynchronies function and does not need any callback.

Feature 4) Forget / Reset password

Firebase would send user a reset password email with a link which directs user to a reset password webpage. The default email template is multilingual and customisable. Here are the examples of English and Tradition Chinese version:

By using setLanguageCode(code: String) function, different lingual emails will be sent to user. Here is the list of supported languages and some examples:

  1. en — English
  2. en_gb — English (UK)
  3. zh_tw — Traditional Chinese
  4. zh_cn — Simplified Chinese

* Please note that you have to create custom email action handlers to support multilingual email template after you customise the template content.

Option 1 (Easier) : By Firebase Console

Steps for sending reset password email to user

Option 2: Programmatically

By using sendPasswordResetEmail(email: String) , user will receive a reset password email sent from Firebase Console. By clicking the link embedded in the email, user will be directed to the reset password webpage. The following is the default template of Firebase project.

Default email template for resetting password

There could be some exceptions thrown in the function:

  1. FirebaseAuthInvalidUserException —When Firebase cannot find an account with the sent account email address.
  2. FirebaseAuthInvalidCredentialsException: The email address is badly formatted, e.g. example@!?!?!?.com

Are you curious with the case the user account is disabled by admin? It would NOT throw an exception and the reset password email can be successfully sent! Firebase only throws an error when user tries to reset password at the reset password webpage. In my opinion, this is not perfect and should be better for Android SDK to throw an exception in this case.

The overall flow of reset password at the webpage:

* Please note that after resetting email address, the original user credential will be no longer valid and user must sign in again to renew his token, else all the other functions for updating personal information will throw a FirebaseAuthInvalidUserException .

Feature 5) Update password

Update password is straight forward by calling updatePassword(password: String) function. The password must consist of at least 6 characters.

  1. FirebaseAuthInvalidUserException: The user account has been disabled by an administrator.
  2. FirebaseAuthWeakPasswordException — The given password is invalid. [ Password should be at least 6 characters ]

Feature 6) Update email

Updating email has some differences with updating password although it is also calling one line of code updateEmail(newEmail: String).

There is a confirmation email sent to user after the login email has been changed successfully at Firebase server. The email template is not customisable due to the Firebase policy of spam prevention. Here is an example of the confirmation email:

Possible exceptions:

  1. FirebaseAuthUserCollisionException:
    Case 1: The email address is currently in use by another account.
    Case 2: Although the email address is not currently occupied by another account, it was another user’s initial email for sign-up.
  2. FirebaseAuthInvalidUserException: The user account has been disabled by an administrator.
  3. FirebaseAuthInvalidCredentialsException: The email address is badly formatted.

Feature 7) Delete user account

Deleting a user account is as simple as just calling delete() function of the current logged in user object. However, there is still one possible failure case:

  1. FirebaseAuthInvalidUserException: The user account has been disabled by an administrator.

* Please note that deleted account is not recoverable and developer should warn user at the app side for better user experience.

Customise Email template

Two kinds of email have been covered above — Reset password email and update email address email. However, only the reset password email template can be changed by admin freely. The update email address template is prohibited due to the Firebase policy of spam prevention. You can customise the password reset email template in the following page:

Steps for customising password reset email template

The original password reset email template is just very simple and contains three Firebase tags:

  1. %LINK% (required): Link where users can reset their password
  2. %APP_NAME%: Your app’s public name
  3. %EMAIL%: User’s email address
Email template example for resetting password

With the help of HTML code and Firebase tags, we could customise the layout and content. See the example below:

Example of customised email template

Limitations

To prevent the abuse of account creation, Firebase limits only 100 accounts can be created from the same IP address in an hour. It is not convenient during development and QA stage. It is able to change this quota temporarily from the Firebase console.
。Max number of sign-ups per IP address per hour: 100
。Schedule time: Within the current year (365 days)
。Max day range: 7 days
The settings can take up to an hour to take effect.

Steps for configuring the sign-up quota (per IP in an hour)
Sign-up Quota configuration setting dialog

Summary

  1. Firebase Authentication provides a lot of sign-up options and one of them is email/ password.
  2. Firebase SDK provides functions for signing up, signing in, signing out, updating email and password, resetting password and deleting account.
  3. Almost all functions except the one for signing out are asynchronised functions which have 3 callbacks to listen for different events. They are OnCompleteListener, OnSuccessListener and OnFailureListener.
  4. OnCompleteListener is fired when there is a response from Firebase system no matter the request is succeed or not.
  5. OnSuccessListener is fired when the request is accepted and done in the Firebase system.
  6. OnFailureListener is fired when the request is rejected in the Firebase system.
  7. Only non-occupied email addresses and non-initial sign-up email addresses are capable to be used for updating the login email address.
  8. Default reset password email can be sent to user with different languages by calling a function setLanguageCode(locale: String) .
  9. Only reset password template can be customised in Firebase system. After customising the reset password email template, custom email action handlers must be implemented in order to support multilingual feature.
  10. Only 100 new accounts can be created in each hour from the same IP. It can be temporarily configured up to 1000 new accounts with max duration of 7 days.

--

--

Mobile Lead @REAL Messenger Inc. https://real.co Focus on Android & iOS Native programming.