Firebase Google Sign In Authentication Jetpack Compose
Steps:
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
How to Add google-services.json file
<resources>
<string name="app_name">Firebase Project</string>
<string name="default_web_client_id">568467537274-q87d4fhj5nbqpc29r6o2.apps
.googleusercontent.com</string>
</resources>
How to find the SHA1 key for our APK
If you don't find signing report
MainActivity
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
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)
}
}
}