DEV Community

Abdul Rehman
Abdul Rehman

Posted on

Firebase UI for Authentication Android Kotlin

Here I will present you the way to use the Firebase UI for Firebase Authentication. Obviously you first have to create an android studio based Android Kotlin Project. Also, you have to create a firebase project. Go to the Tools menu in your Android Studio and then goto the firebase. It will openup a new sidebar menu where it will guide you to do the authentications.

Here you need to click
Select Google Authentication
Now click on Connect to Firebase button
connect to firebase in android studio
Here you need to create a new firebase project or choose any existing project which you want to use.

New Firebase Project

Now you need to click on Connect button
Connect to firebase project

Now your project is connected you can safely close this window.

You are safe to close this window

Now, when you come back to your android studio, you will see this connected sign in the right sidebar.

Firebase Connected

**

Enable Authentication in Firebase Console

**

Now it's time to enable the authentications in your firebase console project. For this, goto the Firebase Console and select your project and open it. Now click Authentication from the Build menu like shown in image below

Autentication Menu

Now click on Get started

Get Started

This will open Authentication Providers list. From here, select, anonymous, email, and Google Authenticators.

Google Autenticator

To use the Google Authenticator, you have to do one more step, for which you have to go back to your android studio project and have to select your SHA Key.

SHA-1 Error

Open the Project Settings, and add SHA-1 by scrolling down and clicking the button which says to add the SHA keys.

add SHA-1

To find the SHA-1 key for your Android project in Android Studio using Gradle, you can use the following command in the terminal. This SHA-1 key is necessary for configuring your Firebase project settings.

  1. Open Android Studio and navigate to your project.
  2. Open the Terminal window in Android Studio. You can do this by going to View > Tool Windows > Terminal.
  3. In the Terminal, navigate to the app directory of your project if you are not already there. You can use the cd command to change directories. For example:
   cd /path/to/your/project/app
Enter fullscreen mode Exit fullscreen mode
  1. Run the following Gradle command to generate the signing report, which includes the SHA-1 key:
   ./gradlew signingReport
Enter fullscreen mode Exit fullscreen mode

Note: If you are on Windows, you might need to use gradlew.bat instead of ./gradlew:

   gradlew.bat signingReport
Enter fullscreen mode Exit fullscreen mode
  1. After running the command, you will see output in the Terminal that includes the SHA-1 key. Look for a section that resembles the following:
   Variant: debug
   Config: debug
   Store: /path/to/your/debug.keystore
   Alias: AndroidDebugKey
   MD5: XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX
   SHA1: XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX
   SHA-256: XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX
   Valid until: Monday, January 1, 2030
Enter fullscreen mode Exit fullscreen mode
  1. Copy the SHA-1 key from the output and use it in your Firebase project settings.

This command generates a signing report for all build variants, including the debug and release variants. Make sure to use the correct SHA-1 key for the variant you are configuring (e.g., debug for development, release for production).

Now you can see that the all three of Auth providers are enabled just like shown in the following picture.

Auth providers list

Add Firebase SDK into your Android Studio Kotlin Project

Now you need to come back to your android studio project and you can either click on the "Add the Firebase Authentication SDK to your app" Button.

Image description

To add the Firebase Bill of Materials (BOM) to your Android Studio project using a build.gradle.kts (Kotlin DSL) file, you need to follow these steps:

  1. Open your build.gradle.kts file: This file is typically located in the app directory of your project.

  2. Add the Firebase BOM dependency: The Firebase BOM helps you manage the versions of Firebase libraries. You can add it to the dependencies block of your build.gradle.kts file.

  3. Add the specific Firebase libraries you need: Use the implementation function to add the specific Firebase libraries you want to use.

Here is an example of how to do this:

plugins {
    id("com.android.application")
    id("org.jetbrains.kotlin.android")
}

android {
    compileSdk = 33

    defaultConfig {
        applicationId = "com.example.yourapp"
        minSdk = 21
        targetSdk = 33
        versionCode = 1
        versionName = "1.0"

        testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        getByName("release") {
            isMinifyEnabled = false
            proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro")
        }
    }
}

dependencies {
    implementation("org.jetbrains.kotlin:kotlin-stdlib:1.8.0")
    implementation("androidx.core:core-ktx:1.8.0")
    implementation("androidx.appcompat:appcompat:1.5.1")
    implementation("com.google.android.material:material:1.6.1")
    implementation("androidx.constraintlayout:constraintlayout:2.1.4")

    // Add the Firebase BOM
    implementation(platform("com.google.firebase:firebase-bom:31.1.1"))

    // Add specific Firebase libraries
    implementation("com.google.firebase:firebase-analytics-ktx")
    implementation("com.google.firebase:firebase-auth-ktx")
    implementation("com.google.firebase:firebase-firestore-ktx")
    // Add other Firebase libraries as needed
}

Enter fullscreen mode Exit fullscreen mode

Explanation:

  • Firebase BOM: The line implementation(platform("com.google.firebase:firebase-bom:31.1.1")) adds the Firebase BOM to your project. This helps manage the versions of Firebase libraries.
  • Specific Firebase Libraries: The lines implementation("com.google.firebase:firebase-analytics-ktx"), implementation("com.google.firebase:firebase-auth-ktx"), and implementation("com.google.firebase:firebase-firestore-ktx") add specific Firebase libraries to your project. You can add more libraries as needed.

Additional Steps:

  • Sync Your Project: After adding the dependencies, click on the "Sync Now" link that appears at the top of the build.gradle.kts file or go to File > Sync Project with Gradle Files.
  • Add Firebase Configuration: Make sure you have added the google-services.json file to your project. This file is downloaded from the Firebase console and should be placed in the app directory.

By following these steps, you will have successfully added the Firebase BOM and the necessary Firebase libraries to your Android Studio project using the build.gradle.kts file.

Add AuthActivity to handle Authentication

Using Firebase Authentication UI is a straightforward way to implement authentication in your Android application. Firebase Authentication UI provides a pre-built UI for common authentication flows, such as email/password, phone authentication, and social providers like Google, Facebook, and Twitter.

Based on the official FirebaseUI documentation, here are the easy-to-follow steps to integrate FirebaseUI for authentication in your Android project:

Add the Google Services Plugin :

  • In your project-level build.gradle file, add the Google services classpath:

      // Top-level build file where you can add configuration options common to all sub-projects/modules.
    plugins {
    alias(libs.plugins.android.application) apply false
    alias(libs.plugins.kotlin.android) apply false
    id("com.google.gms.google-services") version "4.4.2" apply false
    }
    
  • In your app-level build.gradle file, apply the Google services plugin:

      plugins {
    alias(libs.plugins.android.application)
    alias(libs.plugins.kotlin.android)
    id("com.google.gms.google-services")
    }
    
    

Add FirebaseUI Dependencies

Add the necessary dependencies to your build.gradle.kts file:

dependencies {
    // Add the Firebase BOM
    implementation(platform("com.google.firebase:firebase-bom:31.1.1"))

    // Add Firebase Authentication
    implementation("com.google.firebase:firebase-auth-ktx")

    // Add FirebaseUI Auth
    implementation("com.firebaseui:firebase-ui-auth:9.0.0")

    // Required only if Facebook login support is required
    // Find the latest Facebook SDK releases here: https://goo.gl/Ce5L94
    implementation("com.facebook.android:facebook-android-sdk:8.x")
}
Enter fullscreen mode Exit fullscreen mode

Enable Sign-In Methods in Firebase Console

  1. Open the Firebase Console:

  2. Enable Sign-In Methods:

    • In the Firebase Console, go to the Authentication section.
    • Enable the sign-in methods you want to support (e.g., Email/Password, Google, Facebook, etc.).
  3. Configure Google Sign-In:

    • If you enabled Google Sign-In, download the updated google-services.json file and replace the existing one in your project.
    • Specify your app's SHA fingerprint in the Firebase Console.
  4. Configure Facebook and Twitter:

    • If you enabled Facebook or Twitter sign-in, add the necessary string resources to your strings.xml file:
     <resources>
         <!-- Facebook application ID and custom URL scheme (app ID prefixed by 'fb'). -->
         <string name="facebook_application_id" translatable="false">YOUR_APP_ID</string>
         <string name="facebook_login_protocol_scheme" translatable="false">fbYOUR_APP_ID</string>
     </resources>
    

Create an Activity for Sign-In

Create a new activity (e.g., AuthActivity) to handle the FirebaseUI sign-in flow.

package com.any.of.your.package

import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.widget.Button
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.firebase.ui.auth.AuthUI
import com.firebase.ui.auth.FirebaseAuthUIActivityResultContract
import com.firebase.ui.auth.data.model.FirebaseAuthUIAuthenticationResult
import com.google.firebase.FirebaseApp
import com.google.firebase.auth.FirebaseAuth

class AuthActivity : AppCompatActivity() {
    private lateinit var auth: FirebaseAuth
    // Choose authentication providers
    val providers = arrayListOf(
        AuthUI.IdpConfig.EmailBuilder().build(),
        // AuthUI.IdpConfig.PhoneBuilder().build(),
        AuthUI.IdpConfig.GoogleBuilder().build(),
        // AuthUI.IdpConfig.FacebookBuilder().build(),
        // AuthUI.IdpConfig.TwitterBuilder().build(),
    )


    private val signInLauncher = registerForActivityResult(
        FirebaseAuthUIActivityResultContract(),
    ) { res ->
        onSignInResult(res)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        setContentView(R.layout.activity_auth)
        auth = FirebaseAuth.getInstance()
        // See: https://developer.android.com/training/basics/intents/result
        val signInLauncher = registerForActivityResult(
            FirebaseAuthUIActivityResultContract(),
        ) { res ->
            this.onSignInResult(res)
        }
        val btnLogin = findViewById<Button>(R.id.btnAuth)
        btnLogin.setOnClickListener {


            // Create and launch sign-in intent
            val signInIntent = AuthUI.getInstance()
                .createSignInIntentBuilder()
                .setAvailableProviders(providers)
                .setLogo(R.drawable.ic_launcher_foreground) // Set logo drawable
                .setTheme(R.style.Base_Theme_LiveVitalsMonitoring) // Set theme
                .build()
            signInLauncher.launch(signInIntent)
          }

    }

    private fun onSignInResult(result: FirebaseAuthUIAuthenticationResult) {
        val response = result.idpResponse
        if (result.resultCode == RESULT_OK) {
            // Successfully signed in
            val user = FirebaseAuth.getInstance().currentUser
            // Go to the main activity or perform other actions
            startActivity(Intent(this, MainActivity::class.java))
            finish()
        } else {
            // Sign in failed. If response is null the user canceled the
            // sign-in flow using the back button. Otherwise check
            // response.getError().getErrorCode() and handle the error.
            if (response == null) {
                // User pressed back button
                finish()
            } else {
                // Handle error
                // response.getError().getErrorCode()
                if (response == null) {
                    Log.w("SignInActivity", "Sign-in cancelled by user")
                    Toast.makeText(this, "Sign-in cancelled", Toast.LENGTH_SHORT).show()
                } else {
                    Log.e("SignInActivity", "Sign-in error: ${response.error?.localizedMessage}", response.error)
                    Toast.makeText(this, "Sign-in failed: ${response.error?.localizedMessage}", Toast.LENGTH_LONG).show()
                }
            }
        }
    }
}

Enter fullscreen mode Exit fullscreen mode

Google Services Runtime Error

This error, "Check your google-services plugin configuration, the default_web_client_id string wasn't populated," indicates an issue with your Firebase project setup and how your Android application is configured to use Google Sign-In.

Here's a breakdown of what's happening and how to fix it:


The Problem

When you use FirebaseUI-Auth for Google Sign-In, it expects a default_web_client_id to be present in your google-services.json file. This client ID is crucial for the secure communication between your Android app and Google's authentication servers.

The error message means:

  • google-services.json is missing or incorrect: You might not have the google-services.json file in your Android app's app/ directory, or the file you have is outdated/incomplete.
  • Missing default_web_client_id: Even if google-services.json is present, it might not contain the oauth_client entry with client_type of 3 (which corresponds to the web client ID) that FirebaseUI needs for Google Sign-In.

Solutions

1. Download and Replace google-services.json

This is the most common solution. You need to ensure your Android project has the correct and up-to-date configuration file from your Firebase project.

  1. Go to your Firebase Project: Open your Firebase console (console.firebase.google.com) and navigate to your project.
  2. Project settings: Click on the gear icon (Project settings) next to "Project Overview."
  3. Your apps: In the "Your apps" section, select your Android app.
  4. Download google-services.json: Click the "Download google-services.json" button.
  5. Replace the existing file: Copy the newly downloaded google-services.json file into your Android project's app/ directory (e.g., your_project/app/google-services.json). Overwrite any existing file.
  6. Clean and Rebuild:
    • In Android Studio, go to Build > Clean Project.
    • Then, go to Build > Rebuild Project.
    • Run your app again.

2. Verify Google Sign-In is Enabled

Ensure that Google Sign-In is enabled for your Firebase project.

  1. Firebase Console: In your Firebase project, go to Authentication in the left-hand menu.
  2. Sign-in method: Click on the "Sign-in method" tab.
  3. Enable Google: Make sure Google is enabled. If not, enable it and save the changes. This step will also ensure that the necessary OAuth client IDs are generated in your Firebase project, which are then included in your google-services.json file.

3. Check build.gradle (Project Level)

Ensure you have the Google services plugin applied at the project level.

In your project-level build.gradle file (e.g., your_project/build.gradle), make sure you have:

buildscript {
    repositories {
        google()
        mavenCentral()
    }
    dependencies {
        // ...
        classpath 'com.google.gms:google-services:4.4.1' // Or the latest version
    }
}

allprojects {
    repositories {
        google()
        mavenCentral()
    }
}
Enter fullscreen mode Exit fullscreen mode

4. Check build.gradle (App Level)

Ensure you have the Google services plugin applied and Firebase Bill of Materials (BOM) for dependency management at the app level.

In your app-level build.gradle file (e.g., your_project/app/build.gradle), ensure these lines are present:

plugins {
    id 'com.android.application'
    id 'com.google.gms.google-services' // Apply this plugin
    id 'org.jetbrains.kotlin.android' // If using Kotlin
}

android {
    // ...
}

dependencies {
    // Import the Firebase BoM
    implementation(platform("com.google.firebase:firebase-bom:32.8.1")) // Or the latest version
    // When using the BoM, you don't specify versions in Firebase library dependencies

    // Declare the dependency for the Firebase Authentication library
    // and other Firebase products you want to use
    implementation 'com.google.firebase:firebase-auth-ktx'
    implementation 'com.firebaseui:firebase-ui-auth:8.0.2' // Or the latest version for FirebaseUI-Auth

    // ... other dependencies
}
Enter fullscreen mode Exit fullscreen mode

Crucially, make sure id 'com.google.gms.google-services' is applied at the very bottom of your app/build.gradle file, after all other plugins or apply plugin statements.


5. Validate AuthActivity.kt Code (Line 21)

The stack trace points to AuthActivity.kt:21. This means the error is triggered when your AuthActivity tries to build the Google Sign-In configuration. The most common cause is missing the default_web_client_id when constructing the AuthUI.IdpConfig.GoogleBuilder.

Ensure your AuthActivity.kt code (or equivalent) for setting up FirebaseUI for Google Sign-In looks something like this:

// Inside your AuthActivity or a method where you build the sign-in intent
private val signInLauncher = registerForActivityResult(FirebaseAuthUIActivityResultContract()) { result ->
    // Handle the sign-in result
}

// ...

val providers = arrayListOf(
    AuthUI.IdpConfig.GoogleBuilder().build() // This is where the error occurs if default_web_client_id is missing
    // Add other providers like Email, Phone, etc. if needed
)

// Create and launch sign-in intent
val signInIntent = AuthUI.getInstance()
    .createIntentBuilder()
    .setAvailableProviders(providers)
    .build()

signInLauncher.launch(signInIntent)
Enter fullscreen mode Exit fullscreen mode

The AuthUI.IdpConfig.GoogleBuilder().build() call automatically tries to read the default_web_client_id from your google-services.json. If it's not there, you get this error.


In Summary

The error is a direct consequence of your Firebase project's Google Sign-In configuration not being correctly reflected in your Android app's google-services.json file. The primary solution is to ensure you have the latest and correct google-services.json file in your app/ directory, downloaded directly from your Firebase project settings.

Add Google Cloud Project to Firebase Project

To add a Google Cloud project to your existing Firebase project, you need to follow these steps:

  1. Create a Google Cloud Project If you haven't already created a Google Cloud project, you can do so by following these steps:

Go to the Google Cloud Console.
Click on the project drop-down and select "New Project."
Enter a project name and click "Create."

  1. Link Your Google Cloud Project to Firebase If you already have a Firebase project, you can link it to your Google Cloud project. Hereโ€™s how:

Go to the Firebase Console.
Select your existing Firebase project.
In the project overview page, click on the gear icon (Settings) next to "Project Overview" and select "Project settings."
In the "Project settings" page, go to the "Integrations" tab.
Under the "Google Cloud Platform" section, click on the "Link to Google Cloud Platform" button.
Follow the prompts to link your Firebase project to your Google Cloud project.

  1. Add Firebase to Your Google Cloud Project If you want to add Firebase to an existing Google Cloud project, follow these steps:

Go to the Firebase Console.
Click on "Add project" and then "Add Firebase to your Google Cloud project."
Select the Google Cloud project you want to add Firebase to.
Follow the prompts to complete the setup.

Top comments (0)