Firebase Authentication

Most apps need to know the identity of a user. Knowing a user’s identity allows an app to securely save user data in the cloud and provide the same personalized experience across all of the user’s devices. Firebase Authentication provides backend services, easy-to-use SDKs, and ready-made UI libraries to authenticate users to your app. It supports authentication using passwords, phone numbers, popular federated identity providers like Google, Facebook and Twitter, and more. Firebase Authentication integrates tightly with other Firebase services, and it leverages industry standards like OAuth 2.0 and OpenID Connect, so it can be easily integrated with your custom backend.

Why Firebase Phone Authentication?

For implementing phone authentication you need to pay for SMS service, but with firebase, you can do it for FREE, isn’t it awesome? The free plan of firebase has Ten Thousand Verification per month. That’s enough for the starter apps I guess, but yes if you exceed this limit, you need to pay.

Benefits of using Phone Authentication

When you use phone number authentication, you have many benefits like

Preventing Fake Users:

When you use phone authentication, the user can’t be able to register for multiple accounts, as for each account a unique phone number is needed.

Increase User Value:

When you have all the users verified by a phone number the value of your user base increases.

Increased Security and User Experience:

Nowadays more people using apps and remembering passwords are a headache for many users, so they end up using weak passwords. Using phone authentication increases security and user experience, as the user does not need to create and remember passwords, they will enter their number and then they can receive a temporary authentication code by SMS.

How does it work?

To sign a user into your app, you first get authentication credentials from the user. These credentials can be the user’s email address and password, or an OAuth token from a federated identity provider. Then, you pass these credentials to the Firebase Authentication SDK. Our backend services will then verify those credentials and return a response to the client. After a successful sign in, you can access the user’s basic profile information, and you can control the user’s access to data stored in other Firebase products. You can also use the provided authentication token to verify the identity of users in your own backend services.

Advantages of using Firebase in general:

  • Super easy and quick to implement.
  •  No server-side configuration needed. No PHP Scripts and No Database Designs.
  •  Real Time update without using GCM.
  •  Autoscaling built-in
  •  Can start for free (only need to start paying once we hit 50 connections)
  •  Robust APIs for Javascript (including several frameworks like Angular), iOS, and Android
  •  Built-in support for authentication services like Facebook, Google, and Twitter
  •  Declarative Security Rules model allows us to enforce read/write privileges and data validation throughout the tree

Disadvantages of Firebase can be sum up in the following:

  • Need to build indexes manually
  • May need to build “event log” manually as well (in separate sub-tree?)
  •  Implementation of REST API could be difficult on embedded platforms
  •  Data validation rules do not support complex objects directly (you’d need to validate individual child nodes separately)

Enabling Firebase Auth

  1. The first thing you need to do is go to https://firebase.google.com/and make an account to gain access to their console. After you gain access to the console you can start by creating your first project.
  2. Give the package name of your project in which you are going to integrate the Firebase. Here the google-services.json file will be downloaded when you press add app button.
  3. Next, go to your project dashboard. Find the Auth and click get started. Go to set up a sign-in method and choose Email & Password and enable it.

Now we are ready to start our Android project. We are going to create a simple app which contains firebase authentication and profile management. Overall we are going to see how to add Login, Registration, Forgot Password, Change Email, Change Password & finally Sign Out option.

Set up Firebase Authentication for Android, Connect your app to Firebase

  • Install the Firebase SDK.
  • In the Firebase console, add your app to your Firebase project.

Check current auth state

Declare an instance of FirebaseAuth
private FirebaseAuth mAuth;

EmailPasswordActivity.java

In the onCreate() method, initialize the FirebaseAuth instance.
mAuth = FirebaseAuth.getInstance();

Give the package name of your project in which you are going to integrate the Firebase. Here the google-services.json file will be downloaded when you press add app button. Next go to your project dashboard. Find the Auth and click get started. Go to set up sign in method and choose Email & Password and enable it.You can also use the provided authentication token to verify the identity of users in your own backend services.


EmailPasswordActivity.java

When initializing your Activity, check to see if the user is currently signed in.

                      @Override
                      public void onStart() {
                      super.onStart();
                    // Check if user is signed in (non-null) and update UI accordingly.
                      FirebaseUser currentUser = mAuth.getCurrentUser();
                      updateUI(currentUser);
                       }

EmailPasswordActivity.java

Sign up new users, Create a new createAccount method which takes in an email address and password, validates them and then creates a new user with the createUserWithEmailAndPassword method.

                     mAuth.createUserWithEmailAndPassword(email, password)
                     .addOnCompleteListener(this, new OnCompleteListener() {
                     @Override
                     public void onComplete(@NonNull Task task) {
                     if (task.isSuccessful()) {
                   // Sign in success, update UI with the signed-in user's information
                     Log.d(TAG, "createUserWithEmail:success");
                     FirebaseUser user = mAuth.getCurrentUser();
                     updateUI(user);
                     } else 
                     {
                  // If sign in fails, display a message to the user.
                     Log.w(TAG, "createUserWithEmail:failure", task.getException());
                     Toast.makeText(EmailPasswordActivity.this, "Authentication failed.",
                     Toast.LENGTH_SHORT).show();
                     updateUI(null);
                     }
                 // ...
                     }
                     });

EmailPasswordActivity.java

Add a form to register new users with their email and password and call this new method when it is submitted. You can see an example in our quickstart sample. Sign in existing users, Create a new signing method which takes in an email address and password, validates them, and then signs a user in with the signInWithEmailAndPassword method.

                     mAuth.signInWithEmailAndPassword(email, password)
                     .addOnCompleteListener(this, new OnCompleteListener() {
                     @Override
                     public void onComplete(@NonNull Task task) {
                     if (task.isSuccessful()) {
                  // Sign in success, update UI with the signed-in user's information
                     Log.d(TAG, "signInWithEmail:success");
                     FirebaseUser user = mAuth.getCurrentUser();
                     updateUI(user);
                     } else {
                  // If sign in fails, display a message to the user.
                     Log.w(TAG, "signInWithEmail:failure", task.getException());
                     Toast.makeText(EmailPasswordActivity.this, "Authentication failed.",
                     Toast.LENGTH_SHORT).show();
                     updateUI(null);
                     }
                 // ...
                     }
                     });

EmailPasswordActivity.java

Add a form to sign in users with their email and password and call this new method when it is submitted. You can see an example in our quickstart sample. Access user information, If a user has signed in successfully you can get their account data at any point with the getCurrentUser method.

                    FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
                    if (user != null) {
                 // Name, email address, and profile photo Url
                    String name = user.getDisplayName();
                    String email = user.getEmail();
                    Uri photoUrl = user.getPhotoUrl();
               // Check if user's email is verified
                    boolean emailVerified = user.isEmailVerified();
              // The user's ID, unique to the Firebase project. Do NOT use this value to
              // authenticate with your backend server, if you have one. Use
              // FirebaseUser.getIdToken() instead.
                    String uid = user.getUid();
                      }

Optional: Configure ProGuard

When using Firebase Authentication in your app along with ProGuard add the following flags to your pro-guard-rules.pro file to ensure that your app works correctly:

  • keep attributes Signature
  • keep attributes *Annotation*

Firebase is one of the effective platforms that have made the task of the app developers simpler to much extent. Firebase is the best option for any Business applications. It has everything you need to make your App successful. Are you looking to setup Firebase account Please Contact Us or drop us a line at info@spgon.com


Author: Vineela Devi Chalumuri – Android Developer
Source: SimplifiedCoding