You are currently viewing Integrate Google Sign-In with Firebase Authentication

Integrate Google Sign-In with Firebase Authentication

When it comes to third party backend authentication services for iOS apps, the first that comes to mind for sure is Firebase Authentication. By using Firebase Authentication, iOS developers can skip the hassle of setting up a secure backend server and only focus on the mobile side implementation.

Even though Firebase Authentication and Google Sign-in for iOS are both products of Google, they do not automatically integrate with each other.

In this article, I will show you, step-by-step on how to set up Firebase for your iOS project and integrate it with Firebase Authentication.


Prerequisite

This article is the continuation of my previous article Google Sign-In Integration in iOS. If you do not have an iOS app that is already integrated with Google Sign-in, I highly recommend you to go through the previous article before proceeding with this one.

As a quick recap, here’s where we left off:

Google Sign-In Integration in iOS
Google Sign-in integration in iOS

We have successfully integrated Google Sign-in into our sample app, which means users can sign in to the sample app using their Gmail account without any problem.

With that being said, let’s get right into Firebase Authentication integration.


Create Firebase Project

Head over to Firebase Console and create a Firebase project for your sample app.

Create a Firebase project
Create a Firebase project

After clicking on “Add Project”, you will be presented with a list of Google Cloud Platform projects. Go ahead and select the project that you created in Google APIs Console during the Google Sign-in integration.

Select a Google Cloud Platform project to add to Firebase
Select a Google Cloud Platform project to add to Firebase

After clicking “Continue”, you will be asked to enable Google Analytics for your project. You can disable it for now because Google Analytics is not required for Firebase Authentication integration.

Disable Google Analytisc for Firebase Authentication
Disable Google Analytics

After disabling Google Analytics, click “Create Project” to create your Firebase project.


Add Firebase to App

In order to add Firebase to your sample app, click on the “iOS” icon right below the project name to kick start the process.

Add iOS app to Firebase project
Add iOS app to Firebase project

Register App

The first step is to register your sample app to the Firebase project.

Fill in your sample app’s bundle ID and app nickname then click “Register app” to proceed. You can leave the App Store ID blank for now.

Register iOS app for Firebase project
Register iOS app for Firebase project

Download Config File

In this step, you need to download the GoogleService-Info.plist which contains information on the Firebase project you just created and add it to your Xcode project.

After that, make sure that the plist file has been added to the app target.

Ensure GoogleService-Info.plist added to the app target
Ensure GoogleService-Info.plist added to the app target

Once everything is done, click “Next” to proceed to the next step.

Add Firebase SDK

In this step, we will use CocoaPods to install the Firebase Authentication SDK. Go ahead and open the Podfile that we created during the Google Sign-in integration and add in the following:

pod 'Firebase/Auth'

Here’s how your Podfile should look like:

Add Firebase Authentication SDK to Podfile
Add Firebase Authentication SDK to Podfile

After that, close your Xcode project, fire up the Terminal app, navigate to your sample app project location and run pod install to install the Firebase Authentication SDK.

Add Initialization Code

The SDK installation might take a while to finish. Once the installation is completed, open your Xcode project using the workspace file (.xcworkspace) and navigate to AppDelegate.swift.

Add the following line of code at the top of the file to import the Firebase SDK.

import Firebase

After that, add the following line of code in application(_:didFinishLaunchingWithOptions:) to initialize Firebase during app launch.

FirebaseApp.configure()
Configure Firebase in AppDelegate.swift
Configure Firebase in AppDelegate.swift

With all that in place, build and run your sample app to make sure it can be executed without any problem.

Read the Get Started Guide for iOS

This is the last step of the process and you can basically skip this step and just click “Continue to console” to finish up the entire process.

Finishing up the add app to Firebase process
Finishing up the add app to Firebase process

Enable Google Sign-In for Firebase Authentication

Up until this point, the last bit of configuration left is to enable Google Sign-in for Firebase Authentication.

You can follow the flow as shown in the image below to make Google as one of the sign-in providers of Firebase Authentication.

Enable Google Sign-in for Firebase Authentication
Enable Google Sign-in for Firebase Authentication

With that, you have completed the set up needed for Firebase. It is time to head over to Xcode and write some code.


Authenticate with Firebase

Let’s get started by replacing the hardcoded OAuth client ID with the client ID value contained in GoogleService-Info.plist. You can retrieve the client ID value from the plist file using the following line of code.

FirebaseApp.app()?.options.clientID
Retrieve client ID from GoogleService-Info.plist using Swift
Retrieve client ID from GoogleService-Info.plist

After that, we will need to modify the sign(_:didSignInFor:withError:) delegate method so that the sample app will authenticate with Firebase after a user finishes signing in with Google.

func sign(_ signIn: GIDSignIn!,
          didSignInFor user: GIDGoogleUser!,
          withError error: Error!) {
    
    // Check for sign in error
    if let error = error {
        if (error as NSError).code == GIDSignInErrorCode.hasNoAuthInKeychain.rawValue {
            print("The user has not signed in before or they have since signed out.")
        } else {
            print("\(error.localizedDescription)")
        }
        return
    }
    
    // Get credential object using Google ID token and Google access token
    guard let authentication = user.authentication else {
        return
    }
    let credential = GoogleAuthProvider.credential(withIDToken: authentication.idToken,
                                                   accessToken: authentication.accessToken)
    
    // Authenticate with Firebase using the credential object
    Auth.auth().signIn(with: credential) { (authResult, error) in
        if let error = error {
            print("Error occurs when authenticate with Firebase: \(error.localizedDescription)")
        }
            
        // Post notification after user successfully sign in
        NotificationCenter.default.post(name: .signInGoogleCompleted, object: nil)
    }

}

As can be seen from the code snippet above, once a user successfully signed in with Google, we will retrieve the credential object using the Google ID token and access token. After getting the credential object, we will use it to authenticate with Firebase.

Lastly, let’s head over to the view controller and import the Firebase SDK.

import Firebase

After that, modify the signOutButtonTapped(_ sender: UIButton) method to perform Firebase sign out once a user successfully signed out from Google.

@objc func signOutButtonTapped(_ sender: UIButton) {
    // Sign out from Google
    GIDSignIn.sharedInstance()?.signOut()
    
    // Sign out from Firebase
    do {
        try Auth.auth().signOut()
        
        // Update screen after user successfully signed out
        updateScreen()
    } catch let error as NSError {
        print ("Error signing out from Firebase: %@", error)
    }
}

With that, we have completed all the steps and code changes required for Firebase Authentication integration. You can run your sample app to test out the integration.

Go ahead and perform a sign-in action using your sample app. Once you successfully signed in, head over to Firebase Console and verify that a new user has been created.

New user created in Firebase console
New user created in Firebase console

Congratulations! After all this hard work, you have successfully integrated Google Sign-In with Firebase Authentication. 🥳


Wrapping Up

I hope this article can give you a good idea on what should be done when it comes to integrating Google Sign-in with Firebase Authentication.

I will be covering some other topics related to Google Sign-in and Firebase in the near future. If you would like to get notified when a new article comes out, you can follow me on Twitter and subscribe to my monthly newsletter.

Thanks for reading and happy coding! 👨🏼‍💻


Further Readings


👋🏻 Hey!

While you’re still here, why not check out some of my favorite Mac tools on Setapp? They will definitely help improve your day-to-day productivity. Additionally, doing so will also help support my work.

  • Bartender: Superpower your menu bar and take full control over your menu bar items.
  • CleanShot X: The best screen capture app I’ve ever used.
  • PixelSnap: Measure on-screen elements with ease and precision.
  • iStat Menus: Track CPU, GPU, sensors, and more, all in one convenient tool.