Firebase authentication in Android using Kotlin

Pratibha Burde
4 min readApr 22, 2021

I will walk you through Firebase authentication in android quickly step by step, as you are up to this you may have basic knowledge of android programming and project set up.

Firebase is the server provided by the google to your android client. Instead of create whole server you can use this firebase as your backend you can authenticate your user, store data , retrieve data, send cloud messaging, push notification, crashlytics, analytics to your app.

We are specifically going through Authentication here so that includes Sign up For firebase, Sending verification email to user email address, Sign in if you are verified.

Basic requirements,

  1. you should have google account
  2. Android studio

Create android project and go to Firebase console https://console.firebase.google.com/u/0/

Once you are login go to add project option enter relevant project name-> contine->select default account that will take moment

choose android icon

android package name should match with your project package name copy paste it. Name is optional but you can give name of project, and SHA1 key is unique key for your project.

How to get SHA1 key-> Go to gradle option right to android studio

Double click on signingReport and you’ll get SHA1 in logcat section

Then click on Register button on console, it the walk you through the firebase configuration in your project just simply follow it.

Copy google-servoces.json file to app folder of project. click Next

Edit the project level and app level gradle file accordingly.

Basically add google service and firebase dependency to your proejct.

implementation platform(‘com.google.firebase:firebase-bom:27.1.0’) if you add this bom file you don't have to add version of other dependencies of firebase. Click Next and continue to Console. and you have added firebase to your project.

Go to Authentication section and get started

To to sign in method tab Enable Email/Password as we are authenticating with Email and password while doing it you will see email link option that we are not covering in this document. And we are done with firebase side configuration.

Sign Up

Fetch the email id and password from as input from user and provide it while sign up

val auth: FirebaseAuth = Firebase.auth

Define FireBaseAuth in the object class so that it can be accessible allover the app, its singleton thing.

auth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(this) { task ->
if (task.isSuccessful) {
// Sign in success, update UI with the signed-in user's information
Log.d(FirebaseUtils.TAG, "createUserWithEmail:success")
val user = auth.currentUser
sendVerificationEmail(user)
auth.signOut()
finish()
} else {
// If sign in fails, display a message to the user.
Log.w(FirebaseUtils.TAG, "createUserWithEmail:failure", task.exception)
Toast.makeText(
baseContext, "Authentication failed.",
Toast.LENGTH_SHORT
).show()
//updateUI(null)
}
}

sendVerificationEmail() will send verification link to the user’s email account when user double click on link he/she will get verified.

private fun sendVerificationEmail(user: FirebaseUser?) {
user?.sendEmailVerification()?.addOnCompleteListener { task ->
if (task.isSuccessful) {
Log.d(FirebaseUtils.TAG, "Email sent.")
}else{
Toast.makeText(
this, "Couldn't Send Verification Email",
Toast.LENGTH_SHORT
).show()
}
}
}

Sign in

auth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(this) { task ->
if (task.isSuccessful) {
// Sign in success, update UI with the signed-in user's information
Log.d(FirebaseUtils.TAG, "signInWithEmail:success")
// setupFirebaseAuth()
} else {
// If sign in fails, display a message to the user.
Log.w(FirebaseUtils.TAG, "signInWithEmail:failure", task.exception)
Toast.makeText(
baseContext, "Authentication failed.",
Toast.LENGTH_SHORT
).show()
}
}

Above code is for sign in you can add it in on login button click

But below redirecting to the project we have to verify if user is verified, to check it call below method in onCreate

private var mAuthListener: AuthStateListener? = null

define it on class level, this is listner that listen the state change of login.

private fun setupFirebaseAuth() {
Log.d(FirebaseUtils.TAG, "setupFirebaseAuth: started.")
mAuthListener = AuthStateListener {
val user = auth.currentUser
if (user != null) {
//check if email is verified
if (user.isEmailVerified) {
Log.d(FirebaseUtils.TAG, "onAuthStateChanged:signed_in:" + user.uid)
Toast.makeText(
this,
"Authenticated with: " + user.email,
Toast.LENGTH_SHORT
).show()
val user = auth.currentUser
// Now you can login inside the app like call dashboard activity.

}
} else {
Log.d(FirebaseUtils.TAG, "onAuthStateChanged:signed_out")
}
}
}

Register listener

override fun onStart() {
super.onStart()
FirebaseAuth.getInstance().addAuthStateListener(mAuthListener)
}

Unregister listener

override fun onStop() {
super.onStop()
if (mAuthListener != null) {
FirebaseAuth.getInstance().removeAuthStateListener(mAuthListener)
}
}

You can check firebase console now

This is how Authentication works.

Thank you!!

--

--