Firebase Google Sign In Authentication Jetpack Compose

Firebase Google Sign In Authentication Jetpack Compose

Firebase Google Sign In Authentication Jetpack Compose

In this tutorial we will learn to integrate Google Sign In authentication using firebase. We are using Android Studio Koala latest version at the time of writing this tutorial to use firebase and Google signing method we need to add some dependency.

Steps:

1. Create Android Project
2. Add dependency
3.  Create Firebase  Project and add firebase with android app
4. Enable Goggle authentication
5. Design you Google signing Screen (Google SignInScreen)
6. MainActivity

Download Android Studio Latest Version

How to add dependency?

We can directly add the dependency but it is a little different as we do with older version of android studio. 

Lets see how we add in the latest version of Android Studio Iguana 

Step 1- Go to build.gradle.kts(Module :app)

 (A) Add in 

plugins {

 id("com.google.gms.google-services")

}

(B) Add in 

dependencies{

    implementation(libs.firebase.auth)

    implementation(libs.androidx.navigation.compose)

}

build.gradle.kts(Module: app)


plugins {
    alias(libs.plugins.androidApplication)
    alias(libs.plugins.jetbrainsKotlinAndroid)
    id("com.google.gms.google-services")
}

android {
    namespace = "com.codingbihar.firebaseproject"
    compileSdk = 34
    defaultConfig {
        applicationId = "com.codingbihar.firebaseproject"
        minSdk = 26
        targetSdk = 34
        versionCode = 1
        versionName = "1.0"

        testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
        vectorDrawables {
            useSupportLibrary = true
        }
    }

    buildTypes {
        release {
            isMinifyEnabled = false
            proguardFiles(
                getDefaultProguardFile("proguard-android-optimize.txt"),
                "proguard-rules.pro"
            )
        }
    }
    compileOptions {
        sourceCompatibility = JavaVersion.VERSION_1_8
        targetCompatibility = JavaVersion.VERSION_1_8
    }
    kotlinOptions {
        jvmTarget = "1.8"
    }
    buildFeatures {
        compose = true
    }
    composeOptions {
        kotlinCompilerExtensionVersion = "1.5.1"
    }
    packaging {
        resources {
            excludes += "/META-INF/{AL2.0,LGPL2.1}"
        }
    }
}

dependencies {

    implementation(libs.androidx.core.ktx)
    implementation(libs.androidx.lifecycle.runtime.ktx)
    implementation(libs.androidx.activity.compose)
    implementation(platform(libs.androidx.compose.bom))
    implementation(libs.androidx.ui)
    implementation(libs.androidx.ui.graphics)
    implementation(libs.androidx.ui.tooling.preview)
    implementation(libs.androidx.material3)
    implementation(libs.androidx.navigation.compose)
    implementation(libs.firebase.auth)
    implementation(libs.play.services.auth)
    testImplementation(libs.junit)
    androidTestImplementation(libs.androidx.junit)
    androidTestImplementation(libs.androidx.espresso.core)
    androidTestImplementation(platform(libs.androidx.compose.bom))
    androidTestImplementation(libs.androidx.ui.test.junit4)
    debugImplementation(libs.androidx.ui.tooling)
    debugImplementation(libs.androidx.ui.test.manifest)
}

Step 2- Go to libs.versions.toml(Version Catalog) here we add versions and libraries

(A) In the [versions]  section add

googleServices = "4.4.1"

firebaseAuth = "22.3.1"

navigationCompose = "2.7.7"

(B) In [libraries] section add the following

google-services = { group = "com.google.gms", name = "google-services", version.ref = "googleServices" }

firebase-auth = { group = "com.google.firebase", name = "firebase-auth", version.ref = "firebaseAuth" }

androidx-navigation-compose = { group = "androidx.navigation", name = "navigation-compose", version.ref = "navigationCompose" }

libs.versions.toml(Version Catalog)


[versions]
agp = "8.3.2"
kotlin = "1.9.0"
coreKtx = "1.12.0"
junit = "4.13.2"
junitVersion = "1.1.5"
espressoCore = "3.5.1"
lifecycleRuntimeKtx = "2.7.0"
activityCompose = "1.8.2"
composeBom = "2024.04.00"
googleServices = "4.4.1"
playServicesAuth = "21.0.0"
firebaseAuth = "22.3.1"
navigationCompose = "2.7.7"

[libraries]
androidx-core-ktx = { group = "androidx.core", name = "core-ktx", version.ref = "coreKtx" }
junit = { group = "junit", name = "junit", version.ref = "junit" }
play-services-auth = { group = "com.google.android.gms", name = "play-services-auth", version.ref = "playServicesAuth" }
androidx-junit = { group = "androidx.test.ext", name = "junit", version.ref = "junitVersion" }
androidx-espresso-core = { group = "androidx.test.espresso", name = "espresso-core", version.ref = "espressoCore" }
androidx-lifecycle-runtime-ktx = { group = "androidx.lifecycle", name = "lifecycle-runtime-ktx", version.ref = "lifecycleRuntimeKtx" }
androidx-activity-compose = { group = "androidx.activity", name = "activity-compose", version.ref = "activityCompose" }
androidx-compose-bom = { group = "androidx.compose", name = "compose-bom", version.ref = "composeBom" }
androidx-ui = { group = "androidx.compose.ui", name = "ui" }
androidx-ui-graphics = { group = "androidx.compose.ui", name = "ui-graphics" }
androidx-ui-tooling = { group = "androidx.compose.ui", name = "ui-tooling" }
androidx-ui-tooling-preview = { group = "androidx.compose.ui", name = "ui-tooling-preview" }
androidx-ui-test-manifest = { group = "androidx.compose.ui", name = "ui-test-manifest" }
androidx-ui-test-junit4 = { group = "androidx.compose.ui", name = "ui-test-junit4" }
androidx-material3 = { group = "androidx.compose.material3", name = "material3" }
google-services = { group = "com.google.gms", name = "google-services", version.ref = "googleServices" }
firebase-auth = { group = "com.google.firebase", name = "firebase-auth", version.ref = "firebaseAuth" }
androidx-navigation-compose = { group = "androidx.navigation", name = "navigation-compose", version.ref = "navigationCompose" }

[plugins]
androidApplication = { id = "com.android.application", version.ref = "agp" }
jetbrainsKotlinAndroid = { id = "org.jetbrains.kotlin.android", version.ref = "kotlin" }

Add firebase with Android App

Go to firebase console and login by using the email which you use to sign in with android studio
Create a new project with a name as you want
Go to firebase official website and go to the Console
Create a Project with a name here it is Firebase Project

Create a new firebase project

Click the check box and then continue button

Create a new firebase project step 2

Click on Create project button  (No need to enable Google analytic to this project in my case)

Create a new firebase project step 3

Press on Continue this is our project is created

Create a new firebase project step 4


Create a new firebase project step 5

Click on Android logo and Register app

Click on Android logo and Register app

Register app

Now enter the Name, package name and SHA1

Now enter the Name, package name and SHA1

No need to add SDK click on Next step
Download google-services.json file we will use this in our android app and click Next and continue to console.

Download google-services.json file
Click Next and continue

Go to authentication  Get started and enable Google authentication on clicking Google (No need to enable
Go to authentication

Get started

enable Google authentication

enable Google authentication press next

enabled Google authentication

How to Add google-services.json file

By default project is in Android View click om Android and select Project

click om Android and select Project

Copy the google-services.json and paste it by right click on app and add clint_id  from google-services.json in string also

<resources>
<string name="app_name">Firebase Project</string>
<string name="default_web_client_id">568467537274-q87d4fhj5nbqpc29r6o2.apps
.googleusercontent.com</string>
</resources>

Copy the google-services.json and paste it by right click on app

Copy the google-services.json and paste it by right click on app

How to find the SHA1 key for our APK

Go to Gradle > Task > android >  signing report and press enter key

Go to Gradle > signing report

Select app:signingReport and press enter key

Select app:signingReport
Select app:signingReport and press enter key

If you don't find signing report

If you don't find signing report

1. Click on Build Tool Settings and 
2. Go to Gradle Settings.. and 
3. Click on Experimental at the bottom and check the box as the fig and 
4. Sync Project with Gradle Files wait an  few seconds now you are able to see use gradle app:signingReport to get SHA1    

Click on Build Tool Settings

Click on Experimental

signingReport

MainActivity

Copy this code →

import ...          
          
class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            FirebaseProjectTheme {
                // A surface container using the 'background' color from the theme
                Surface(
                    modifier = Modifier.fillMaxSize(),
                    color = MaterialTheme.colorScheme.background
                ) {
                    GoogleSignInScreen()
                    
                }
            }
        }
    }
}

Google SignInScreen

Copy this code →

import ...

@Composable
fun GoogleSignInScreen() {
    Column(
        Modifier.fillMaxSize(),
        verticalArrangement = Arrangement.Center,
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        var user by remember { mutableStateOf(Firebase.auth.currentUser) }
        val launcher = rememberFirebaseAuthLauncher(
            onAuthComplete = { result ->
                user = result.user
            },
            onAuthError = {
                user = null
            }
        )
        val token = stringResource(R.string.default_web_client_id)
        val context = LocalContext.current
        Column {
            if (user == null) {
                Text("Not logged in")
                Button(onClick = {
                    val gso =
                        GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                            .requestIdToken(token)
                            .requestEmail()
                            .build()
                    val googleSignInClient = GoogleSignIn.getClient(context, gso)
                    launcher.launch(googleSignInClient.signInIntent)
                }) {
                    Text(text = "google")
                }
            }
            else {
                Text("Welcome ${user!!.displayName}")
                Button(onClick = {
                    Firebase.auth.signOut()
                    user = null
                }) {
                    Text("Sign out")
                }
            }
        }
    }
}

@Composable
fun rememberFirebaseAuthLauncher(
    onAuthComplete: (AuthResult) -> Unit,
    onAuthError: (ApiException) -> Unit
): ManagedActivityResultLauncher {
    val scope = rememberCoroutineScope()
    return rememberLauncherForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
        val task = GoogleSignIn.getSignedInAccountFromIntent(result.data)
        try {
            val account = task.getResult(ApiException::class.java)!!
            val credential = GoogleAuthProvider.getCredential(account.idToken!!, null)
            scope.launch {
                val authResult = Firebase.auth.signInWithCredential(credential).await()
                onAuthComplete(authResult)
            }
        } catch (e: ApiException) {
            onAuthError(e)
        }
    }
}

OUTPUT:
Output Firebase Google Sign In Authentication Jetpack Compose
Previous Post Next Post

Contact Form