How To Implement Firebase Authentication In Android/Kotlin

HOW TO IMPLEMENT FIREBASE AUTHENTICATION IN ANDROID/Kotlin (EXAMPLE CODE)


Please Subscribe Youtube| Like Facebook | Follow Twitter

For Java follow this article

Introduction

In this article we will learn how to use firebase authentication in our app. You can use it to identify user in your application. Firebase Authentication provides various Sign-in providers through which you can authenticate user such as Anonymous, Email/Password, Google and Facebook etc. Firebase Auth uses user’s uid to uniquely identify user. Firebase store authentication info in its cache so once user is authenticated then authentication will work offline as well.  

In Anonymous provider you can sign-in user anonymously which allows user to create temporary account to authenticate without providing details i.e username, password, email etc. Keep in mind that if user sign-in using Anonymous Sign-in method and if user clears app data then previous Anonymous Authentication user’s uid will be lost and new user’s uid will be generated in Anonymous Signing-in again. However using other Sign-in providers method if app data is cleared then same uid and user details will be restored by again signing-in using same account. You can also convert an anonymous account to a permanent account later if required.

Our Example

In our example we have textview which shows current login user details and button which allows user to authenticate using Anonymous, Email/Password or Google Sign-in providers. On app start we will check if user is not signed-in then we will display button which will authenticate user and if user is already signed in then we will display user details on textview.

Requirements:

  1. Android Project/App in which authentication to be implemented
  2. Firebase Project

Note: First you need to create Firebase Project and then connect your app to it. You can follow this article to set it up.

Steps

Follow below steps

1) Enable sign-in provider in Firebase Authentication

2) Code Authentication Logic

3) Run and test your app

1) Enable sign-in provider in Firebase Auth

First go to Firebase and open your Firebase Project and click on Authentication.

Click on setup sign-in method

Enable Email/Password, Google and Anonymous providers

2) Code Authentication Logic

First add firebase-auth and firebase-ui-auth library at app level build.gradle file

implementation 'com.google.firebase:firebase-auth:19.3.1'
implementation 'com.firebaseui:firebase-ui-auth:6.2.0'

Application screen contains textview and button below is layout file code

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:orientation="vertical"
    android:gravity="center"
    >
    <TextView
        android:id="@+id/userDetails"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:visibility="gone"
        />
    <Button
        android:id="@+id/authenticate"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Authenticate"
        android:visibility="gone"
        android:onClick="authenticate"
        />
</RelativeLayout>

On app start we have called checkSigInStatus() method which will check if user is signed-in then display user details else display authentication button to authenticate user.

private fun checkSigInStatus() {
	authUser = FirebaseAuth.getInstance().currentUser
	if (authUser != null) {
		userDetails.text = """
			Current Logged in User
			User Id = ${authUser!!.uid}
			User Name = ${authUser!!.displayName}
			Email = ${authUser!!.email}
			""".trimIndent()
		authenticate.visibility = View.GONE
		userDetails.visibility = View.VISIBLE
	} else {
		userDetails.visibility = View.GONE
		authenticate.visibility = View.VISIBLE
	}
}

On authenticate button click we will display authentication screen to user to authenticate using Anonymous, Email/Password, Google providers. Result of Authentication will be reported inside onActivityResult() method, we have passed result code RC_SIGN_IN=1. Add FirebaseTheme inside res->values->styles.xml

<style name="FirebaseTheme" parent="Theme.AppCompat.Light.DarkActionBar">
</style>
fun authenticate(view: View?) {
	// Choose authentication providers
	val providers = Arrays.asList(
			AnonymousBuilder().build(),
			EmailBuilder().build(),
			GoogleBuilder().build()
	)
	// Create and launch sign-in intent
	startActivityForResult(
			AuthUI.getInstance()
					.createSignInIntentBuilder()
					.setAvailableProviders(providers)
					.setTheme(R.style.FirebaseTheme)
					.build(),
			RC_SIGN_IN)
}

onActivityResult() method we have checked if authentication is successful then display user details else toast Sign in Failed message.

 override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
	super.onActivityResult(requestCode, resultCode, data)
	if (requestCode == RC_SIGN_IN) {
		if (resultCode == Activity.RESULT_OK && FirebaseAuth.getInstance().currentUser != null) {
			//display logged in user info
			checkSigInStatus()
		} else {
			Toast.makeText(this, "Sign in Failed. Please Sign in To Continue", Toast.LENGTH_SHORT).show()
		}
	}
}

Whole Code

Project level build.gradle

buildscript {
    ext.kotlin_version = '1.4.0-rc'
    repositories {
        jcenter()
        google()
        maven { url 'https://dl.bintray.com/kotlin/kotlin-eap' }
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.5.3'
        classpath 'com.google.gms:google-services:4.3.3'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
    }
}

allprojects {
    repositories {
        google()
        jcenter()
        
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

App level build.gradle

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'kotlin-android'
apply plugin: 'com.google.gms.google-services'
android {
    compileSdkVersion 28
    buildToolsVersion "29.0.3"
    defaultConfig {
        applicationId "com.programtown.example"
        minSdkVersion 17
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'androidx.appcompat:appcompat:1.0.2'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test.ext:junit:1.1.0'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.1'

    implementation 'com.google.firebase:firebase-auth:19.3.1'
    implementation 'com.firebaseui:firebase-ui-auth:6.2.0'
    implementation "androidx.core:core-ktx:+"
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
}
repositories {
    maven { url 'https://dl.bintray.com/kotlin/kotlin-eap' }
    mavenCentral()
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:orientation="vertical"
    android:gravity="center"
    >
    <TextView
        android:id="@+id/userDetails"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:visibility="gone"
        />
    <Button
        android:id="@+id/authenticate"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Authenticate"
        android:visibility="gone"
        android:onClick="authenticate"
        />
</RelativeLayout>

styles.xml

<resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>
    <style name="FirebaseTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    </style>

</resources>

MainActivity.kt

package com.programtown.example

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.firebase.ui.auth.AuthUI
import com.firebase.ui.auth.AuthUI.IdpConfig.*
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.FirebaseUser
import kotlinx.android.synthetic.main.activity_main.*
import java.util.*

class MainActivity : AppCompatActivity() {

    var authUser: FirebaseUser? = null

    override fun onCreate(savedInstanceState: Bundle?) {

        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        checkSigInStatus()
    }

    private fun checkSigInStatus() {
        authUser = FirebaseAuth.getInstance().currentUser
        if (authUser != null) {
            userDetails.text = """
                Current Logged in User
                User Id = ${authUser!!.uid}
                User Name = ${authUser!!.displayName}
                Email = ${authUser!!.email}
                """.trimIndent()
            authenticate.visibility = View.GONE
            userDetails.visibility = View.VISIBLE
        } else {
            userDetails.visibility = View.GONE
            authenticate.visibility = View.VISIBLE
        }
    }

    fun authenticate(view: View?) {
        // Choose authentication providers
        val providers = Arrays.asList(
                AnonymousBuilder().build(),
                EmailBuilder().build(),
                GoogleBuilder().build()
        )
        // Create and launch sign-in intent
        startActivityForResult(
                AuthUI.getInstance()
                        .createSignInIntentBuilder()
                        .setAvailableProviders(providers)
                        .setTheme(R.style.FirebaseTheme)
                        .build(),
                RC_SIGN_IN)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == RC_SIGN_IN) {
            if (resultCode == Activity.RESULT_OK && FirebaseAuth.getInstance().currentUser != null) {
                //display logged in user info
                checkSigInStatus()
            } else {
                Toast.makeText(this, "Sign in Failed. Please Sign in To Continue", Toast.LENGTH_SHORT).show()
            }
        }
    }

    companion object {
        private const val RC_SIGN_IN = 1
    }
}

3) Run and test your app

First authenticating using Anonymous method (continue as guest). In this method only user’s uid will be shown after authentication.

Now clearing apps data and then authenticating using email/password (Sign in with email) method, after authentication user name and email will be displayed on screen.

After authentication clear apps data and sign in again using email by providing previous account email and password. After signing in account information will be restored.

In user tab you can see list of registered users

Conclusion

So in this post we have learned how to implement Firebase Authentication in android application to identify/authenticate user.

Please Subscribe Youtube| Like Facebook | Follow Twitter


Leave a Reply

Your email address will not be published. Required fields are marked *