Site icon Howtodoandroid

Simple Steps To Sign-In With Google On Firestore Android

Firebase Login with Google

Are you want to set up a user Sign-in with google in your android application, In this tutorial I have explained about login with firebase Sign-In in android.

Firebase Authentication is a secure authentication system provided by Google that allows developers to manage user authentication for their applications. It enables developers to create custom authentication flows and integrate with popular identity providers such as Facebook, Twitter, and Google.

Steps to create and configure Android App on Google Firebase Account

Create a Firebase developer account at Firebase Console.

  1. Go to the Firebase console.
  2. Click Add Project > Enter Project Name > Continue > Create Project
Create a new project on the Firebase console

3. Once the project is created, Select the ‘Android’ platform SDK to configure the android application.

4. Enter the application package name and register the app.

5. Once registered, you can able to download the google-service.json file to integrate it into the Android application.

google-service.json file

6. Then click Next > and Continue to console.

7. also enable the google sign-in on firebase authentication.

go to Firebase Console > Authentication > Sign-in method

Now we are done with the project set up on the firebase console. let’s move to the android studio to create an android project.

Android Studio Firebase Login Set up

Create a new project, go to tools > Firebase.

It will open the Assistant for firebase. Select Authentication > Authentication With Google [kotlin].

Then, click Connect to firebase. It will redirect to the firebase console and ask you to select the project for the login setup. choose the newly created project and switch back to android studio.

It will sync all the project configurations to the android studio project like the google-service.json file will be copied to your app directory.

Once the firebase is connected to the app. then click on the Add the firebase authentication SDK to your app. It will add the dependencies for the firebase auth configurations. The dependencies are,

In the project-level build.gradle, add the classpath,

buildscript { dependencies { classpath 'com.google.gms:google-services:4.3.14' } }
Code language: JavaScript (javascript)

In the module-level build.gradle file.

plugins { ... id 'com.google.gms.google-services' } dependencies { ... implementation 'com.google.firebase:firebase-firestore-ktx:24.4.0' implementation platform('com.google.firebase:firebase-bom:31.0.2') implementation 'com.google.firebase:firebase-auth' implementation 'com.google.android.gms:play-services-auth:20.4.0' }
Code language: JavaScript (javascript)

done with adding project dependencies. let’s create a login screen UI design.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <com.google.android.material.textview.MaterialTextView android:id="@+id/label" android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="center" android:text="Login Sample App" android:textAppearance="@style/TextAppearance.MaterialComponents.Headline5" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" app:layout_constraintVertical_bias="0.31" /> <com.google.android.material.button.MaterialButton android:id="@+id/btnLoginWithGoogle" android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="center" android:text="Login With Goole" android:layout_marginVertical="20dp" android:layout_marginHorizontal="30dp" android:padding="12dp" android:textAppearance="@style/TextAppearance.MaterialComponents.Button" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/label" /> </androidx.constraintlayout.widget.ConstraintLayout>
Code language: HTML, XML (xml)

After done with the login screen design, your Login Activity needs to initialize the sign-in request. To create a sign-in request we need a web client ID for our project. Go to the credential console and copy the web client ID.

also, other important properties are,

setFilterByAuthorizedAccounts – to true so only the Google accounts that the user has authorized before will show up in the credential list. This can help prevent a new account from being created when the user has an existing account registered with the application.

setAutoSelectEnabled – Automatic sign-in is possible when the following criteria are met:

lateinit var oneTapClient: SignInClient lateinit var signInRequest: BeginSignInRequest oneTapClient = Identity.getSignInClient(this) signInRequest = BeginSignInRequest.builder() .setPasswordRequestOptions( BeginSignInRequest.PasswordRequestOptions.builder() .setSupported(true) .build() ) .setGoogleIdTokenRequestOptions( BeginSignInRequest.GoogleIdTokenRequestOptions.builder() .setSupported(true) .setServerClientId(getString(R.string.default_web_client_id)) // Only show accounts previously used to sign in. .setFilterByAuthorizedAccounts(true) .build() ) // Automatically sign in when exactly one credential is retrieved. .setAutoSelectEnabled(true) .build()
Code language: JavaScript (javascript)

After the sign-in request is ready, on click of the login button need to call beginSignIn() with the sign-in request we created. This will start the pending intent to handle the login result.

btnLoginWithGoogle.setOnClickListener { oneTapClient.beginSignIn(signInRequest).addOnSuccessListener { result -> try { startIntentSenderForResult( result.pendingIntent.intentSender, REQ_ONE_TAP, null, 0, 0, 0, null ) } catch (e: IntentSender.SendIntentException) { Log.e("Error", "Couldn't start One Tap UI: ${e.localizedMessage}") } }.addOnFailureListener { Log.d("Error", it.localizedMessage) } }
Code language: JavaScript (javascript)

On click of the login button, it will launch the google authentication UI to enter username and password. If the user already logged in with the same account already it will just show the account to choose from.

After the user enters the username and password or selected the login account, it will redirect to the activity result. use the below code to get the authToken and logged-in user details.

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) when (requestCode) { REQ_ONE_TAP -> { try { val credential = oneTapClient.getSignInCredentialFromIntent(data) val idToken = credential.googleIdToken val username = credential.id val password = credential.password when { idToken != null -> { // Got an ID token from Google. Use it to authenticate // with your backend. Log.d("Debug", "Got ID token.") } password != null -> { // Got a saved username and password. Use them to authenticate // with your backend. mAuth.signInWithEmailAndPassword(username, password) .addOnSuccessListener { Toast.makeText(this, it.user?.email, Toast.LENGTH_SHORT) .show() }.addOnFailureListener { Toast.makeText(this, it.message, Toast.LENGTH_SHORT) .show() } Log.d("Debug", "Got password.") } else -> { // Shouldn't happen. Log.d("Error", "No ID token or password!") } } } catch (e: ApiException) { // ... } } } }
Code language: JavaScript (javascript)

Check Logged-in User

To check the logged-in user, use the below code at the start of the application,

override fun onStart() { super.onStart() // Check if user is signed in (non-null) and update UI accordingly. var currentUser = auth.getCurrentUser() updateUI(currentUser); }
Code language: JavaScript (javascript)

Handle sign-out

When a user signs out of your app, call the One Tap client’s signOut() method. Calling signOut() disables automatic sign-in until the user signs in again.

btnSignOut.setOnClickListener { FirebaseAuth.getInstance().signOut() }

Conclusion

Thanks for reading. Also, you can download the example from GitHub.

Exit mobile version