Authenticate Using Google Sign-In ( Kotlin + Firebase )

Myric September
8 min readOct 3, 2018

In this tutorial we will learn how to authenticate using google sign-in. Google enables us to register/sign-in to our apps using different social accounts such Facebook, Twitter or in our case Google. Let’s get started! 😃

Android studio project

Create a new Android studio project and name it “FirebaseAuthGoogle”. For the Company domain use “myricseptember.com” and ensure that the Include Kotlin support checkbox is selected.

Leave the minimum SDK as it is and click Next. Select “Empty Activity”, than click Next. Name the activity “SignInActivity” than click Finish.

Create a firebase project

The first step is to create a Firebase project within your Firebase Console. Click on Add project:

Name your project “FirebaseAuthGoogle”. Once you’ve given your project a name, read and accepted any terms and conditions, then click the ‘Create project’ button. Once done you should see the following screen indicating that the project was successfully created.

Click the continue button where you will be taken to the welcome screen. On this screen you are given the option to create either an iOS, Android or web app. We are creating an Android app so click on that option:

Another window will open requesting some information relating to your application. Fill in the package name “com.myricseptember.firebaseauthgoogle” than add your SHA 1 key. If you don’t know how to get your SHA key follow these steps:

  • With Android Studio open, click on the Gradle menu on the right to open it.
  • Open the folder structure as follows: FirebaseAuthGoogle -> :app ->Tasks->android -> then double click on ‘signingReport’

Note: if the packages are not showing in the gradle menu just click the refresh button:

A window will open at the bottom from which you can get your SHA1 key:

Note: Remember to select the app option in your Android Studio project once you have your SHA key, see below:

Add the SHA key and click On Register app:

Download the JSON file and place it within your android app as indicated by the arrows then click ‘Next’:

Once you get to the screen below just click next since we will be adding all the necessary gradle dependencies at a later stage. Also after the Add Firebase SDK screen Firebase will try to check if the app has made contact, just click on ‘skip this step’:

Great! Your application is now connected to firebase, but we still have some more work to do. Let’s get to it!

Enable Google Sign-In on Firebase

In your Firebase console on the left click on the ‘Authentication’ item. From the tabs select ‘Sign-In method’ to open the window below. Select the following:

Enable Google Sign-In in the top right corner. Also provide a ‘Project support email’ and click Save.

Add Gradle dependencies

Next, go to your Android Studio project. To enable social authentication we need to add some Firebase dependencies manually. It is import to use the latest Google Login SDK version which you can find here.

Here you’ll find the latest Firebase dependencies.

Open the project level Build.gradle :

Then add the following dependency:

classpath 'com.google.gms:google-services:4.0.1'

Next open the Module:app level gradle dependency:

And add the following dependencies:

dependencies {

//other dependencies

//firebase
implementation 'com.google.firebase:firebase-core:16.0.4'
implementation 'com.google.firebase:firebase-auth:16.0.4'

//play service auth
implementation 'com.google.android.gms:play-services-auth:16.0.1'
}

apply plugin: 'com.google.gms.google-services'

Once all these dependencies have been added, Android studio will require you to sync the project. This will download all the dependencies from the internet and will require you to have an internet connection.

Note: It is very important to ensure that you have “Google Play Services’ installed. You can do so by clicking on ‘Tools’ than selecting ‘SDK Manager’ as seen below:

After clicking on ‘SDK Manager’ the below window should open. Select the ‘Google Play Services’ checkbox and click apply. This will ensure that Sign-In works as expected on the Google Emulator as well.

Create a simple UI

Next we will create a simple UI with a single button in the middle of the screen. You can make your UI pretty but for demo purposes we are going to keep things simple.

Add the following to your “activity_sign_in.xml” xml file:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.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=".SignInActivity"
>

<com.google.android.gms.common.SignInButton
android:id="@+id/google_button"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:padding="8dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
/>

</android.support.constraint.ConstraintLayout>

Since you need to connect to the network to authenticate with Firebase you will need to add the internet permission to your AndroidMenifest.xml:

<uses-permission android:name="android.permission.INTERNET"

Integrating Google SignIn

Within the SignInActivity add the following variables for the GoogleSignInClient and GoogleSignInOptions.

val RC_SIGN_IN: Int = 1
lateinit var mGoogleSignInClient: GoogleSignInClient
lateinit var mGoogleSignInOptions: GoogleSignInOptions

Next add the following method to your code. The method is used to request the user data required by your app such as the users’ ID and basic profile information, email address and Id token. Call this method in your OnCreate() method.

private fun configureGoogleSignIn() {
mGoogleSignInOptions = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build()
mGoogleSignInClient = GoogleSignIn.getClient(this, mGoogleSignInOptions)
}

Add the setupUI() method to set up the OnClickListener for our login button. This method gets called in the OnCreate() method:

private fun setupUI() {
google_button.setOnClickListener {
signIn()
}
}

Next, we add a singIn() method which will be called when the user presses on the log in button. The user will be prompted to select an authentication account. The signInIntent is used to handle the sign in process and for starting the intent the startActivityForResult() is used.

private fun signIn() {
val signInIntent: Intent = mGoogleSignInClient.signInIntent
startActivityForResult(signInIntent, RC_SIGN_IN)
}

Once done the onActivityResult() is called in which the selected google account is retrieved and sent to Firebase for authentication.

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == RC_SIGN_IN) {
val task: Task<GoogleSignInAccount> = GoogleSignIn.getSignedInAccountFromIntent(data)
try {
val account = task.getResult(ApiException::class.java)
firebaseAuthWithGoogle(account)
} catch (e: ApiException) {
Toast.makeText(this, "Google sign in failed:(", Toast.LENGTH_LONG).show()
}
}
}

Note: the implementation for the firebaseAuthWithGoogle() method will be discussed below.

The authentication with Google step is now completed. Next we need to authenticate with Firebase. Declare an instance of the FirebaseAuth object.

private lateinit var firebaseAuth: FirebaseAuth

Then in the onCreate method, get the shared instance of the FirebaseAuth object

firebaseAuth = FirebaseAuth.getInstance()

After a user successfully signs in, gets an ID token from the GoogleSignInAccount object, exchange it for a Firebase credential, and authenticate with Firebase using the Firebase credential:

private fun firebaseAuthWithGoogle(acct: GoogleSignInAccount) {
val credential = GoogleAuthProvider.getCredential(acct.idToken, null)
firebaseAuth.signInWithCredential(credential).addOnCompleteListener {
if
(it.isSuccessful) {

startActivity(HomeActivity.getLaunchIntent(this))
} else {
Toast.makeText(this, "Google sign in failed:(", Toast.LENGTH_LONG).show()
}
}
}

Note: The HomeActivity will be created soon

To avoid the need for the user to sign in every time the app is launched it would be better to check if the user is signed in already. This can be achieved by checking if the current user is already signed in from within the onStart() method:

override fun onStart() {
super.onStart()
val user = FirebaseAuth.getInstance().currentUser
if (user != null) {
startActivity(HomeActivity.getLaunchIntent(this))
finish()
}
}

Create a companion object to open the SignInActivity via intent.

companion object {
fun getLaunchIntent(from: Context) = Intent(from, SignInActivity::class.java).apply {
addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK)
}
}

Great! Everything for authentication is set up. Next we just need to create a second screen (HomeActivity) to which we will navigate once the user is successfully authenticated. You can use this screen to retrieve and display the current user’s information from the Firebase database, but that is out of the scope of this tutorial. We will simply display some text congratulating the user for successfully signing in and have a log out button at the bottom.

Home Screen

Create an Activity called HomeActivity. The activity will look like the screen below once done:

The XML for activity_home.xml should look something like the below:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.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=".HomeActivity"
>


<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:gravity="center"
android:text="@string/congrats_text"
app:layout_constraintBottom_toTopOf="@+id/sign_out_button"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
/>

<Button
android:id="@+id/sign_out_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="36dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:text="@string/sign_out_button"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
/>
</android.support.constraint.ConstraintLayout>

Within HomeActivity add the setupUI() method which will be used to set up the click listener for the sign out button. Call the setupUI() method within your onCreate() method.

private fun setupUI() {
sign_out_button.setOnClickListener {
signOut()
}
}

Next create the signOut() method which will be used to sign the user out of the application.

private fun signOut() {
startActivity(SignInActivity.getLaunchIntent(this))
FirebaseAuth.getInstance().signOut();
}

Finally create a companion object to to open the HomeActivity via intent.

companion object {
fun getLaunchIntent(from: Context) = Intent(from, HomeActivity::class.java).apply {
addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK)
}
}

We’re Done! Let’s run the application and celebrate our hard work.😃

Conclusion

In this article we have built a simple application that makes use of Google authentication. Firebase is great and there is much more you can do with it. I will be posting more Kotlin articles and will be using more of Firebase. I look forward to your feedback and would advise you to take a look at the repo.

Thank you for reading this article. Click the 👏 button, ⭐️ the repo on Github, and follow me on Twitter and on Medium for future articles.

--

--

Myric September

Senior Android Engineer @ Primotion; Johannesburg South Africa; Kotlin star; Speaker; Blogger