Google Sign-In for iOS

Dennis Hills
ITNEXT
Published in
10 min readOct 16, 2018

--

Update (April 2019): Updated the client code to reflect the latest auth changes with AWS SDK for iOS (2.8.0+) and AWS Amplify.

We are continuing to build on using social login providers as a mobile authentication mechanism, allowing your users to authenticate within your iOS cloud-enabled app. In this article, we are going to integrate Google Sign-In into our iOS app. In the previous article, “Facebook Login Using AWS Amplify and Amazon Cognito”, we used Amazon Identity Pool to federate authentication through Facebook Login. Before that article, we used Amazon Cognito User Pools as basic auth to manage our app user directory and each user created a new account and authenticated with their username/password, unique to your app.

With Google Sign-In integration, instead of creating a new account via Cognito User Pools, or federating Facebook, the user can simply choose the Sign in with Google button in your app and authenticate via Google using their Google credentials, all while staying within your app flow.

Note: Your app can support any combination of Facebook, Google, or username/password. You’re not limited to one social provider or basic auth.

The abriddge

Step 1: Google OAuth Client IDs

Goal: The end goal here is to obtain an OAuth Web Client ID and iOS Client ID to utilize Google Sign-in in your app. These client ids are in the form of a URL. You’ll copy both client IDs from the Google developer portal and save them for later.

How it works: To implement Google Sign-in into your iOS app, you need an OAuth Web & iOS Client ID. These Client IDs are part of your Google Developers project. The Web Client ID will be used by Cognito Identity Pools to manage the OAuth flow between Cognito and Google on the server side. The iOS Client ID will be used in your iOS app to authorize the OAuth flow directly with Google allowing your users to authenticate with Google using their Google login credentials.

Implementation: There are a few ways to generate (Web and iOS) Client IDs. The easiest way that I have found is following the ‘start-integrating’ section of the Google Developer portal. This allows you to create a new project or select an existing one, auto-generates the Web Client ID in the background and creates an iOS Client ID for you to copy.

NOTE: The creation and configuration steps for creating OAuth Clients for Google Sign-In is constantly changing, so always refer to the official setup instructions from Google.

Start here:

A. Log into https://developers.google.com/identity/sign-in/ios/start-integrating

B. Scroll down to Get an OAuth client ID and select the CREATE AN OAUTH CLIENT ID button. IGNORE everything else on that page.

C. Follow the steps for your own project as outlined in the animated gif.

Create a new project or select an existing project.

Provide a product name that’ll be shown to the user.

Specify iOS as your specific application environment for OAuth client.

Provide your iOS application bundle identifier (e.g. com.domain.appname)

Select Done.

D. Now, obtain your Web Client ID and iOS Client ID from your Google project credentials page: https://console.developers.google.com/apis/credentials

E. With your project selected, under OAuth 2.0 client IDs, copy and save the Web Client ID (associated with the Web application type) and the iOS Client ID (associated with the iOS type) for the next step.

Step 2: Create a New iOS Project in Xcode

Create a new Swift iOS single view application or use an existing Xcode iOS swift project. We’ll cloud-enable this app using AWS Amplify in the next step.

Step 3: Amplify CLI

Initialize cloud backend for Google Sign-In using Amplify CLI

[Installing the Amplify CLI — First Time]

Before we initialize our backend, we are going to be using the AWS Amplify CLI which is part of the AWS Amplify Toolchain . If you haven’t installed the AWS Amplify CLI before, here’s a quick shortcut. amplify configure is only needed if you have not installed or configured the AWS unified CLI. If you have the AWS CLI installed, the Amplify CLI will utilize those credentials.

$ npm install -g @aws-amplify/cli
$ amplify configure

This is a one-time install. Check out the Get Started tutorial for more details.

[Adding Auth to our iOS App via Amplify CLI]

Launch Mac Terminal in the root of your iOS project folder. Now, we’ll initialize our AWS backend project using the following Amplify command.

$ amplify init

You will be guided through the process of setting up the project. Make sure iOS is selected at the appropriate time.

Next, let’s add authenticated access to our mobile project. We’ll follow the same process as outlined in the Email & Password option tab in the AWS Documentation.

$ amplify add auth

Since we are not choosing the default settings, the values that I used in my app are shown in the image below. Most are defaults you enter through, and others, you have a chance to name your resources.

For this configuration below, I’m adding the basic auth via User Pools along with Google Sign-In as it’s easier to do this in one step and it’s good to offer both a basic login and a social login option for your users.

OAuth Client IDs found here: https://console.developers.google.com/apis/credentials
AWS Amplify CLI — Auth w/Basic auth and Google Sign-In

Push the local configuration changes to your AWS account

$ amplify push

We now have a Cognito User Pools, Identity Pool, authenticated & unauthenticated IAM Roles along with Google as an authentication provider.

Step 4: Set up AWS Mobile SDK for iOS (Cocoapods)

In this example, I’m going to use Cocoapods for dependency management as this is currently the recommended way to integrate AWS SDK into an iOS project. More info on Cocoapods. If you don’t already have pods in your app, you can simply run a $ pod init and it’ll create a fresh Podfile for you. Once you have a Podfile, add the following dependencies to that file.

$ pod init

In your Podfile, add the following dependencies to that file.

https://gist.github.com/mobilequickie/0ad088a2731616462fcd6b556363120c

Pull the SDK libraries into your project:

$ pod install --repo-update

Step 5: AWSConfiguration.json

When using the AWS Amplify CLI to provision backend resources, it produces a file called awsconfiguration.json in the root of your iOS Xcode project. This file contains a description of the resources that you can access via your app and is updated (synced) with your project anytime a resource is added, updated, or deleted by the Amplify Toolchain. This auto-update of the configuration file is one of the great benefits of using the Amplify CLI to provision AWS resources from your local mobile development environment.

You only need to add the awsconfiguration.json file to your Xcode project just once. You can do this by dragging it to your Finder in the Xcode project organizer.

You will be prompted if you want to copy the file. UNCHECK THE COPY ITEMS BOX. The AWS Amplify CLI updates this file when things change. If you check the Destination box, then your project may not receive the updates if copied. If you uncheck the box, this file is updated whenever you modify the project resources via the Amplify CLI.

Step 6: Google Sign-In iOS URL scheme

The Google Sign-in callback flow requires a custom URL scheme to be added to your iOS project. This URL scheme is your OAuth iOS Client ID that you copied in step #3 of Obtain Google Project Credentials (OAuth Client IDs).

To add the custom scheme we are going to edit the Xcode project Info.plist:

Launch Xcode, open its Info.plist file using Right-click > Open As > Source Code.

Your iOS Client ID goes in the string value of the Info.plist but in the REVERSE order.

The reversed client ID is your iOS client ID (in the form of a URL) with the order of the dot-delimited fields reversed. For example:

Custom URL scheme in your iOS project
https://gist.github.com/mobilequickie/133cf95d49dc36a47a2f6d75f0c9e2b0

Now that you’ve configured your Xcode project, you can add Google Sign-In UI to your iOS app managed by the AWSMobileClient and built-in Auth UI as part of the AWS Mobile SDK.

Step 7: Initialize AWSMobileClient

In your root UIViewController or related screen that you want users to sign-up or sign-in, add the following code referenced in the image below:

1. Add the import from line 2

2. Add initializeAWSMobileClient() call to bottom of your viewDidLoad() as shown on line 9

3. Add the new function initializeAWSMobileClient() from line 12–45 to your view controller.

Note: The showSignIn() function does not exist yet. We’ll add that in the next step.

https://gist.github.com/dennisAWS/8fba1d9dc738141452ceeb9f98992f40

Step 8: Add Google Sign-In Drop in UI

Add the showSignIn() function to the same View Controller as above. This is the drop-in auth UI that allows your users to sign-up, sign-in, and reset their passwords. You can customize the background color and image to match your branding. This function is called when the user is signed out or the refresh token has expired for the user. Note: The refresh token for Facebook is usually good for 60 days with no activity. The Google Sign-In refresh token is “long term” so not sure when it expires. The user pools (basic auth) refresh token is developer specific from 1 day to 365 days.

Add the new function showSignIn() from line 12–23 to your view controller.

https://gist.github.com/dennisAWS/30e43e3ba8ab7df79a5fe85973d7543e

Warning. A UINavigationController is required in your iOS app when using Auth UI drop in: The auth UI as part of the AWS Mobile SDK and it requires that your app have a UINavigationController.

To add a UINavigationController to your app, if one does not exist:

Add a UINavigationController to your iOS app: From your Xcode project, select the ViewController in Storyboard then select menu options:

Editor->Embed In -> Navigation Controller.

Step 9: Build and Run Your App

You should see the AWS SDK pre-built sign-in UI for your app as the user is not initially authenticated. The AWS SDK for iOS provides a standard default UI that now allows the user to Sign in via Google along with register (sign-up), trigger “forgot password” functionality, and of course sign-in capabilities built-in along with the default username/email and password fields.

Click on the Sign in with Google button. The user is then redirected and asked to sign in with their Google credentials. Once authenticated, the UI dialog will disappear and you should now see your view controller screen.

At this point, the app user is authenticated through Google and the user now assumes the authenticated IAM role and is granted permissions associated with that role, however, that role still has an empty access policy. This is the same process we went through when the user authenticated with username/password via Cognito User Pools or Facebook. This time, the user authenticated with Google as an identity provider for Cognito Identity Pool.

Final Thoughts

Amazon Cognito is the default choice for both authenticated and unauthenticated flows for all mobile apps connecting to AWS resources. If you don’t require a login or use any other identity provider, such as Facebook or Google, use Cognito Federated Identities (Cognito Identity Pool).

For authenticated users via Google, the AWS Mobile SDK will pass (and act as the identity manager) the authenticated user token to your Cognito Identity Pool in exchange for temporary AWS credentials for that user to make calls to your AWS resources. User access is then defined by the IAM authenticated role. If the user does not authenticate, Cognito Identity Pool still grants AWS credentials and the user’s access is defined by the IAM unauthenticated role.

Want to take a a deeper look into the Cognito Identity Pool integration with Google Sign-In? If you are interested in behind-the-scenes of how the AWS Mobile SDK is working with Amazon Cognito Identity Pool to identify the currently logged in user, check out Google’s “Authenticate with a backend server” guide. This gives you a better appreciation for the AWS Mobile SDK and integration with Amazon Cognito.

Resources

Google Sign-In for your iOS app

AWS Amplify (using the Amplify CLI to cloud-enable our app)

Amazon Cognito User Pool (used for basic auth)

Amazon Cognito Identity Pool (used for federating basic auth and Google Sign-In)

--

--

Mobile Developer. I do mobile stuff. Opinions are always my own.