In the last tutorial, I showed you how to connect an Android App to Firebase. Today I am going to show you how to add Email and Google authentication in Android using FireBase. Or in simple words, we will be adding Email and Google Login in an Android App using Firebase.

 

FirebaseUI

We will be using FirebaseUI Android library for this. The main advantage of using FirebaseUI is that it is secure and hence you don’t have to write complex code of encrypting the user credentials. And it also handles all the cases, right from maintaining user sessions to password recovery.

The below flowchart shows all the cases handled by FirebaseUI.

Firebase Authentication Flowchart

Getting started

Add the following dependency to your app level build.gradle file to use FirebaseUI.

    compile 'com.firebaseui:firebase-ui:1.2.0'

Make sure to add the Fabric repository to your project level build.gradle file. To do so add the highlighted line.

allprojects {
    repositories {
        // ...
        maven { url 'https://maven.fabric.io/public' }
    }
}

Email Authentication

Go to Firebase Console, select your project and click on Authentication tab. Click on Sign-in method, select Email/Password and enable it.

Firebase Email Authentication 2

Now add the following permission to your manifest file.

<uses-permission android:name="android.permission.INTERNET"/>

Now create a  class named Login.java and add the code shown below.

package tec.com.firebasedemo;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;

import com.firebase.ui.auth.AuthUI;
import com.firebase.ui.auth.ErrorCodes;
import com.firebase.ui.auth.IdpResponse;
import com.firebase.ui.auth.ResultCodes;
import com.google.firebase.auth.FirebaseAuth;

import java.util.Arrays;

/**
 * Created by TEC Staff on 11-05-2017.
 */

public class Login extends AppCompatActivity {

    // Choose an arbitrary request code value
    private static final int RC_SIGN_IN = 123;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        FirebaseAuth auth = FirebaseAuth.getInstance();
        if (auth.getCurrentUser() != null) {

            // already signed in
            startActivity(new Intent(Login.this, MainActivity.class));
            finish();

        } else {

            // not signed in
            startActivityForResult(
                    AuthUI.getInstance()
                            .createSignInIntentBuilder()
                            .setProviders(Arrays.asList(new           AuthUI.IdpConfig.Builder(AuthUI.EMAIL_PROVIDER).build()
                                    ))
                            .build(),
                    RC_SIGN_IN);
 
        }
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // RC_SIGN_IN is the request code you passed into startActivityForResult(...) when starting the sign in flow.
        if (requestCode == RC_SIGN_IN) {
            IdpResponse response = IdpResponse.fromResultIntent(data);

            // Successfully signed in
            if (resultCode == ResultCodes.OK) {
                startActivity(new Intent(Login.this,MainActivity.class);
                finish();
                return;
            } else {
                // Sign in failed
                if (response == null) {
                    // User pressed back button
                    Log.e("Login","Login canceled by User");
                    return;
                }

                if (response.getErrorCode() == ErrorCodes.NO_NETWORK) {
                    Log.e("Login","No Internet Connection");
                    return;
                }

                if (response.getErrorCode() == ErrorCodes.UNKNOWN_ERROR) {
                    Log.e("Login","Unknown Error");
                    return;
                }
            }

            Log.e("Login","Unknown sign in response");
        }
    }
}

The above code checks whether a user is already logged in or not. If a user is already logged in, he/she is redirected to the MainActivity, otherwise, the user is asked to Signup via Email as shown below. Make sure to make the Login activity as launcher activity.

Firebase Email Authentication Screen

Now when you run the app and signup using Email, you can see the authenticated User in Firebase console.

Firebase Authentication Console

Google Authentication

Again go to Firebase Console, select your project and click on Authentication tab. Click on Sign-in method, select Google and enable it.

 

Now we need to add SHA Certificate Fingerprint for Google Login to work. For generating SHA go to Android Studio, click on Gradle –> :app –> android and then double click on signingReport.

Firebase with Android

Now open Gradle console and you can see the SHA.

SHA Android Studio

Now open Firebase, click on Settings icon, scroll down and click on Add Fingerprint and copy the generated SHA.

Generated SHA

Now open your Login activity and modify the startActivityForResult code as shown below.

startActivityForResult(
                   AuthUI.getInstance()
                           .createSignInIntentBuilder()
                           .setIsSmartLockEnabled(false)
                           .setProviders(Arrays.asList(new AuthUI.IdpConfig.Builder(AuthUI.EMAIL_PROVIDER).build(),
                                   new AuthUI.IdpConfig.Builder(AuthUI.GOOGLE_PROVIDER).build()
                                   ))
                           .build(),
                   RC_SIGN_IN);

In the above code, we added Google Sign in Builder along with the Email one and also disabled smart lock as it logs in the user automatically without showing the login screen.

Google login screen using Firebase

Now run the app and login with Google. You can see that Firebase shows that user has logged in using Google account.

In the next tutorial, I will show you how to save and retrieve data from Android app to Firebase.

Related Posts

Android

Add Phone Number Authentication in Android (Firebase Tutorial #5)

This tutorial shows how to add Phone Number Authentication in Android app using Firebase. We have used FirebaseUI library for achieving authentication.

Android

Add Shimmer Effect to Android app

Rather than the same old circular loader, you can add shimmer effect to Android app when it is loading. This tutorial shows how you can add shimmer effect to your Android app.

Android

Upload an Image to Firebase Storage (Firebase Tutorial #4)

Today, I am going to show you how to upload an image to Firebase storage and then show that uploaded image in an ImageView in Android.

Subscribe and get a free eBook on 8 Tips to level up your Android Development Skills.

(We hate spam as much as you do)

You have Successfully Subscribed!

%d bloggers like this: