Unlock the Power of Firebase Authentication in Kotlin: Transform Your User Experience Today!

Firebase Authentication is a service provided by Google Firebase that enables developers to authenticate users into their apps. It supports various authentication methods, including email and password, phone numbers, and federated identity providers like Google, Facebook, and Twitter.

In this blog, we’ll explore Firebase Authentication, its various functions, and how to implement them in a Kotlin Android application.

Firebase Authentication

1. Introduction to Firebase Authentication

Firebase Authentication aims to make the process of user authentication simple and secure. It provides backend services, easy-to-use SDKs, and ready-made UI libraries to authenticate users to your app. This ensures that your app’s user data remains secure and helps you manage users effectively.

2. Setting Up Firebase in Your Android Project

To get started with Firebase Authentication, you need to set up Firebase in your Android project. Follow these steps:

  • Create a Firebase Project:
    • Go to the Firebase Console.
    • Click on “Add Project” and follow the on-screen instructions.
  • Add Firebase to Your Android App:
    • In your Firebase project,
    • Register your app with your package name.
    • Download the google-services.json file and place it in the app directory of your Android project.
  • Add Firebase SDK:
    • Open your project-level build.gradle file and add the following classpath:
    • click on the Android icon to add an Android app.
classpath 'com.google.gms:google-services:4.3.10'

Open your app-level build.gradle file and add the Firebase Authentication dependency:

implementation 'com.google.firebase:firebase-auth:21.0.6'
apply plugin: 'com.google.gms.google-services'

sync your project with Gradle files.

3. Authentication Methods

Email and Password Authentication

Email and password authentication is a basic and widely used method for authenticating users. Here’s how to implement it in Kotlin:

  1. Enable Email/Password Authentication:
    • In the Firebase Console, go to Authentication > Sign-in method.
    • Enable Email/Password.
  2. Sign Up with Email and Password:
val auth: FirebaseAuth = FirebaseAuth.getInstance()

fun signUp(email: String, password: String) {
    auth.createUserWithEmailAndPassword(email, password)
        .addOnCompleteListener { task ->
            if (task.isSuccessful) {
                val user = auth.currentUser
                // User sign-up successful
            } else {
                // Sign-up failed
            }
        }
}

3.Sign In with Email and Password:

fun signIn(email: String, password: String) {
    auth.signInWithEmailAndPassword(email, password)
        .addOnCompleteListener { task ->
            if (task.isSuccessful) {
                val user = auth.currentUser
                // User sign-in successful
            } else {
                // Sign-in failed
            }
        }
}

Google Sign-In

Google Sign-In allows users to sign in using their Google account. Here’s how to implement it:

  1. Enable Google Sign-In:
    • In the Firebase Console, go to Authentication > Sign-in method.
    • Enable Google.
  2. Add Google Sign-In Dependencies:
implementation 'com.google.android.gms:play-services-auth:20.0.1'

Configure Google Sign-In:

val gso = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
    .requestIdToken(getString(R.string.default_web_client_id))
    .requestEmail()
    .build()

val googleSignInClient = GoogleSignIn.getClient(this, gso)

Handle Google Sign-In Result:

fun handleGoogleSignInResult(data: Intent) {
    val task = GoogleSignIn.getSignedInAccountFromIntent(data)
    try {
        val account = task.getResult(ApiException::class.java)
        firebaseAuthWithGoogle(account.idToken!!)
    } catch (e: ApiException) {
        // Google Sign-In failed
    }
}

private fun firebaseAuthWithGoogle(idToken: String) {
    val credential = GoogleAuthProvider.getCredential(idToken, null)
    auth.signInWithCredential(credential)
        .addOnCompleteListener(this) { task ->
            if (task.isSuccessful) {
                val user = auth.currentUser
                // Sign-in successful
            } else {
                // Sign-in failed
            }
        }
}

Phone Number Authentication

Phone number authentication allows users to sign in using their phone number. Here’s how to implement it:

  1. Enable Phone Authentication:
    • In the Firebase Console, go to Authentication > Sign-in method.
    • Enable Phone.
  2. Send Verification Code:
fun sendVerificationCode(phoneNumber: String) {
    val options = PhoneAuthOptions.newBuilder(auth)
        .setPhoneNumber(phoneNumber)
        .setTimeout(60L, TimeUnit.SECONDS)
        .setActivity(this)
        .setCallbacks(callbacks)
        .build()
    PhoneAuthProvider.verifyPhoneNumber(options)
}

private val callbacks = object : PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
    override fun onVerificationCompleted(credential: PhoneAuthCredential) {
        signInWithPhoneAuthCredential(credential)
    }

    override fun onVerificationFailed(e: FirebaseException) {
        // Verification failed
    }

    override fun onCodeSent(
        verificationId: String,
        token: PhoneAuthProvider.ForceResendingToken
    ) {
        // Code sent
    }
}

Sign In with Verification Code:

fun signInWithPhoneAuthCredential(credential: PhoneAuthCredential) {
    auth.signInWithCredential(credential)
        .addOnCompleteListener(this) { task ->
            if (task.isSuccessful) {
                val user = auth.currentUser
                // Sign-in successful
            } else {
                // Sign-in failed
            }
        }
}

4. Managing Users

Get Current User

You can get the currently signed-in user using:

val user = FirebaseAuth.getInstance().currentUser
user?.let {
   // User is signed in
}

Sign Out

To sign out the current user:

FirebaseAuth.getInstance().signOut()

Update User Profile

To update the user’s profile:

val user = FirebaseAuth.getInstance().currentUser
val profileUpdates = UserProfileChangeRequest.Builder()
   .setDisplayName("New Name")
   .setPhotoUri(Uri.parse("https://example.com/jane-q-user/profile.jpg"))
   .build()

user?.updateProfile(profileUpdates)
   ?.addOnCompleteListener { task ->
       if (task.isSuccessful) {
           // Profile updated
       }
   }

5. Advanced Features

Email Verification

To send a verification email to the user:

val user = FirebaseAuth.getInstance().currentUser
user?.sendEmailVerification()
   ?.addOnCompleteListener { task ->
       if (task.isSuccessful) {
           // Verification email sent
       }
   }

Password Reset

To send a password reset email:

fun sendPasswordResetEmail(email: String) {
   FirebaseAuth.getInstance().sendPasswordResetEmail(email)
       .addOnCompleteListener { task ->
           if (task.isSuccessful) {
               // Password reset email sent
           }
       }
}

To link multiple authentication providers:

6. Conclusion

Firebase Authentication provides a robust and easy-to-implement solution for user authentication. With support for multiple authentication methods and seamless integration with Firebase services, it helps you build secure and scalable applications. By following the steps and code examples provided in this blog, you can implement and manage Firebase Authentication in your Kotlin Android app effectively. Happy coding!