How to add Facebook and Google login to your Ionic 2 app with Cordova Oauth

Adding third party authentication to a mobile app is one of the most common challenges developers deal with. This feature cannot be excluded from your Ionic 2 app too. In this tutorial,

  • We will start by configuring our machines for Ionic 2 app development
  • We will use Supermodular 2 starter app where we will implement the third-party authentication with Facebook and Google providers using the ng2-cordova-oauth Angular 2 library.
  • Finally, we will configure the side menu so our new screen is included.

Note: The complete source code of this tutorial is available in the ionic2-oauth Github repository.

Download the code

Preparations

Before we begin, make sure you have your machine all set up for Ionic 2.

NodeJS

Download the installer for NodeJS and install the version 6 or greater.

Sass

In order to install Sass, firstly, you should make sure Ruby is installed on your machine since Sass has a Ruby dependency. If you have MAC OS, Ruby is already installed. Otherwise, you should install Ruby and, then, Sass. Depending on your OS, follow the quick instructions included in the official page of Sass.

Ionic and Cordova CLI

Whether you have a previous Ionic/Cordova installation and you want to update it or this is the first time you install them, open your terminal and run the command:

$npm install -g ionic cordova

Note: If you are a Mac or Linux user, the most likely is that you will need “sudo” at the front of this command in order to install the utilities globally.

Android and/or iOS Tools and SDKs

If you plan to build native apps for Android and iOS, you should install Android and iOS tools and SDKs on your machine. Since Ionic is based on Cordova, Cordova provides a very useful guide for installing the requirements for Android platform and iOS platform (Mac OS users only).

Starting a new Ionic 2 App

Supermodular 2 is a free starter template that allows you to start a new Ionic 2 project quickly offering some basic features commonly used in recent mobile applications. We are going to use it in order to build a basic Ionic 2 app with an extremely modular architecture and best software development practices applied.

Clone Github repo

Visit http://github.com/appseed-io/supermodular2 and download or clone the Supermodular 2 app:

$git clone https://github.com/appseed-io/supermodular2.git

Alternatively, it is recommended that you fork the repository since, later, you will be able to push any code you will add to this project straight to your own project repository.

Install libraries

Open a terminal window and navigate to the supermodular2 folder. Install the NodeJS dependencies:

$npm install

Install plugins and platforms

Install all the required Cordova plugins the app needs with the following command:

$ionic state restore

This command will actually restore all the platforms and plugins are included in the package.json file.

Note: In case you do not work on a Mac OS machine, open the package.json file and replace the iOS platform with the Android platform or leave the cordovaPlatforms array empty if you do not want to add a platform yet.

Run the app

In your terminal, make sure you are located in the supermodular2 folder and run the command:

$ionic serve --lab

Scaffold the new module

First of all, let’s just create the very basic structure of our a new module. We will add it where all our modules are collected, in the app.module.ts file by adding the following lines in the highlighted area:

import { OAuthModule } from '../pages/oauth/oauth.module';

and

OAuthModule

Create the oauth folder that is going to contain all the files related to this feature. Then, create the oauth.module.ts file where OAuthModule that we previously imported in the app.module.ts file will be defined.

Copy the code that follows in the oauth.module.ts file. For now, we will declare only the page where we are going to list the authentication providers.

For the template with the list of the authentication providers, create an oauth-providers.list.html file in the oauth/list folder. This should look similar to the code provided in the following snippet:

We call the login() function on the user click so let’s move to the corresponding page for this screen. For the time being, we will leave this function empty since we only want to scaffold the page.

Under the oauth/list path, create an oauth-providers.list.page.ts file and paste the code:

Finally, we will add an entry in our side menu so the user can have access to the screen with the list of the authentication providers we created. In order to do this, we will add the highlighted code in the app.components.ts file.

By now, we should be able to run our app and see the newly added screen:

Implement Login logic

Abstract authentication service

Next, we will implement a service that will perform the tasks associated with the authentication feature such as the user login, logout and the profile information retrieval.

For starters, let’s implement the logic for the login functionality. Create an oauth.service.ts file in the oauth folder and paste the following code in there:

In short, the login() function accepts the provider-source as a parameter and returns a promise for the OAuthToken object. It makes use of the login() function that belongs to the service of a particular authentication provider injected by the getOAuthService function which returns an Interface for the authentication provider (IOathProvider). Finally, it uses the setOAuthToken() function and sets the authentication token in the local storage. Also, we will create a getOAuthToken() function for getting the authentication token back from the local storage each time we need it.

Authentication provider and token interfaces

As we have already mentioned, the IOathProvider should include a login() function. Therefore, we should set the following interface that will act as an abstract type/model for the IOathProvider object. Create an oauth.provider.interface.ts file in the oauth folder and include the following lines in it:

Also, we will set an interface for the OAuthToken. Therefore, create the oauth-token.model.ts under the oauth/models/ path and paste the following code:

Facebook and Google authentication services

As a next step, we should implement the services for each one of the authentication providers our app has, i.e. FacebookOauthProvider and GoogleOauthProvider.

Install dependencies

Here is when the ng2-cordova-oauth library comes handy. We can install it by executing the command:

$npm install ng2-cordova-oauth --save

Also, our app relies on the Cordova InAppBrowser plugin. We are going to install it with:

$ionic plugin add cordova-plugin-inappbrowser

Do not forget to include cordova-plugin-inappbrowser in your package.json file too, so it can be installed with the rest of the plugins anytime you install your project from scratch.

Implement the Facebook and Google authentication providers

Let’s create the facebook-oauth.provider.ts file under the oauth/facebook/ path. In this file, include the code in the snippet:

Here, we import the CordovaOauth and the Facebook classes. In the constructor we initialize the Facebook object by passing the clientId and appScope in the configuration options. We pass these options through Config which is a basically a file with all the variables one should change in order to configure the app with their own settings. The login() function logs in the user and returns a string with the access token as a Promise.

The clientId came from the app you will need to configure with Facebook using the Facebook Developer Dashboard. For more information, refer to the “Facebook and Google applications configuration for developers” section at the bottom of this article.

Similarly, using the CordovaOauth object available by the ng2-cordova-oauth library, we will implement the Google authentication provider with its own login() function. However, here we pass another clientId from Config that corresponds to the application we configured with Google using the Google Developer Console. Again, for more information, refer to the “Facebook and Google applications configuration for developers” section at the bottom of this article.

Therefore, create a google-oauth.provider.ts file and paste the following lines:

Declare services/providers in module

Since we are following a modular architecture, we are going to declare all our services in the oauth.module.ts file. Consequently, open the oauth.module.ts file and add the following lines as highlighted:

Implement root login() function

Now that we have completed the implementation of the login logic, we are going to implement the login() function we left empty in the oauth-providers.list.page.ts file. Simply, we will call the login() function of our oauthService and, if it is executed successfully it will log a related message in the console.

So, replace the contents of the providers.list.page.ts file with the provided code:

Now, we can run the app to make sure the user is able to login successfully. This time we will run it on the iOS simulator since that app uses Cordova plugins. After we hit Facebook, we should be able to see the Facebook login page and, after we enter our credentials, we should be able to see the log message. The same goes for Google authentication too.

Getting User Profile

To begin with, we will add a getProfile() function in our root authentication service, i.e. the oauth.service.ts file. The code we are going to add is the following:

This function will check if the user is authorized so it calls the getProfile() function specifically for a particular authentication provider passing the access token.

Get profile in authentication provider interface

As we mentioned in the previous section, we need a getProfile() function for each authentication provider. Therefore, we will define a getProfile() function in the oauth.provider.interface.ts file by adding the following lines as highlighted:

This function returns an OAuthProfile object.

Create authentication profile interface

In order to define the OAuthProfile interface, create an oauth-profile.model.ts file under the oauth/models/ path and paste the following code:

Get profile in Facebook and Google authentication providers

The getProfile() function we are going to add in the facebook-oauth.provider.ts file is included in the code below. Notice to place the code sections as highlighted in the screen capture.

Here, we request the access token of the user profile, we map the access token we received to a JSON object since it is the result of an observable and we return the user profile as a Promise.

The getProfile() function in the google-oauth.provider.ts file will be really similar to that one of the Facebook authentication provider. Thus, let’s include the following lines in the google-oauth.provider.ts file:

Note: Since Angular 2 uses Observables and Rxjs library to make async calls, make sure you have imported map and toPromise operators in your main.ts:

import 'rxjs/add/operator/toPromise';

Create User Profile template

Let’s create a simple user profile template for displaying the authentication provider, user’s email and name. Under the oauth/profile/ path place the code of the following snippet:

Implement profile page

The page that corresponds to the user profile template should call the getProfile() function of the root authentication service. As a result, create the oauth-profile.page.ts file under the oauth/profile/ path and paste the code that follows:

Declare profile page in authentication module

We should declare the profile page in the oauth.module.ts file by adding the following lines as highlighted:

Navigate user to profile screen

Finally, let’s change the login() function in the oauth-providers.list.page.ts file so the app navigates the user to the profile screen. The code that enables it is provided below:

Final Result

Running the app in the iOS simulator again, we should be able to view the profile screen showing the user profile information.

Facebook and Google applications configuration for developers

Facebook

Facebook Application ID

Firstly, you should create and register a new Facebook Application by following the URL below:

https://developers.facebook.com/apps/

Once the Application is created navigate to the “Settings” page and select “Add Platform”.

Then, select “Website”

and set as “Site URL” the value “http://localhost/”. Also, keep a note of the “App ID” and hit “Save changes”.

Once you create your Facebook App, set the related variables in the config.ts file under the src folder.

On the Facebook Developers platform, select “Add Product” from the side menu and, then, choose “Facebook Login”. Make sure you have enabled “Client OAuth Login” and “Web OAuth Login” and set your “Valid OAuth redirect URIs” to “http://localhost/callback”. At the end, do not forget to hit the “Save changes” button.

Google

Google Application ID

You should create and register a new Google App on Google Developer Console. In the credentials section, choose to create credentials for OAuth client ID.

Then, select “Web application” and set the “Authorized redirect URIs” to “http://localhost/callback”.

Finally, copy the client ID

and set the related variables in the config.ts file.

Need More?

To find authentication with more providers packed with many more features to incorporate in any Ionic 2 mobile app, check out Barebone Ionic 2, the Swiss Army Knife of Ionic2!

References

Tyler Nienhouse for the cover photo


Originally published at http://appseed.io/node/69.