Ionic 3, Angular 4 and Cordova LinkedIn Authentication Tutorial

by Didin J. on Jul 20, 2017 Ionic 3, Angular 4 and Cordova LinkedIn Authentication Tutorial

A comprehensive step by step tutorial on LinkedIn login or authentication using Ionic 3, Angular 4, Cordova, and Native LinkedIn plugin

Almost every Mobile Apps has an authentication feature of sign in with LinkedIn. Fortunately, LinkedIn has the API to accommodate the authentication or login feature that accessible across platform, web, or mobile apps. That's the reason what we make this tutorial with Ionic, Angular, and Cordova to make Linked authentication easy in Mobile Apps.

Table of Contents:

This step by step tutorial of LinkedIn authentication using Ionic 3, Angular 4 and Cordova will be started by setting up an app in the Linkedin developer dashboard. After getting an app ID, as usual, we will start implementing from scratch by creating a new Ionic 3 app. We will use Ionic Cordova Native LinkedIn plugin to implement the LinkedIn login in an Ionic app. In the end, we will show you how to share something on the LinkedIn profile.

Linkedin API Setup

Open your browser then point to the LinkedIn developer portal. LinkedIn Developer uses to integrate with LinkedIn’s powerful APIs to build products that help professionals go farther.

Ionic 3, Angular 4 and Cordova LinkedIn Authentication Tutorial - LinkedIn Developer Portal

Sign in using your linked account by click on the person icon. Click My Apps menu then click 'Create Application' button. Fill the form, all fields with the asterisk should not left blank then click Submit button.

Now, you can see client ID and client secret, write it to your notepad. You can check default application permission that will use in your Ionic 3 application. Add authorized redirect URLs, use this URL 'http://localhost/callback' then click update. Next, open the mobile menu on the left.

Ionic 3, Angular 4 and Cordova LinkedIn Authentication Tutorial - Linked In Android Setup

What you need to do is fill package name and package hash in Android setting section. For this tutorial, we use package name 'com.linkedin.ionic3' for the package that you need to generate it from current 'debug.keystore' for development or your 'release.keystore' for production. To do that, back to the terminal or cmd then type this command to get the SHA1 and SHA256 hash.

keytool -list -v -keystore ~/.android/debug.keystore -alias androiddebugkey -storepass android -keypass android

And the output will be like this.

Alias name: androiddebugkey
Creation date: Nov 8, 2015
Entry type: PrivateKeyEntry
Certificate chain length: 1
Certificate[1]:
Owner: CN=Android Debug, O=Android, C=US
Issuer: CN=Android Debug, O=Android, C=US
Serial number: 5e9752f4
Valid from: Sun Nov 08 22:25:34 WIB 2015 until: Tue Oct 31 22:25:34 WIB 2045
Certificate fingerprints:
     MD5:  0A:2D:96:6B:B8:84:F7:37:2E:7E:83:09:43:BB:B7:D4
     SHA1: 2B:52:02:F0:82:94:34:68:FC:B6:DD:81:1D:3A:66:D7:57:3B:B9:11
     SHA256: B1:40:EB:9D:03:50:A2:0F:F2:D4:1B:6D:AA:F6:F9:6A:57:52:B0:70:5A:3C:87:9E:15:F0:BE:7C:90:00:DA:51
     Signature algorithm name: SHA256withRSA
     Version: 3

Extensions:

#1: ObjectId: 2.5.29.14 Criticality=false
SubjectKeyIdentifier [
KeyIdentifier [
0000: C0 3A D3 06 65 23 89 A1   5D 80 CC 55 88 D8 BD 23  .:..e#..]..U...#
0010: 80 6E 67 01                                        .ng.
]
]

You can find 'debug.keystore' in your Android SDK folder. Now, convert SHA1 and SHA256 to Base64. I'm using these online tools for it. After you get the base64 string that must paste to package hash column then click 'Add' button. As you can see in the picture above there is two package hash (SHA1 and SHA256) and one app package name.


Create Ionic 3 and Angular 4 app

Before creating Ionic 3 and Angular 4 app, make sure your environment exists and updated to the newer version. Type this command for checking the versions.

node -v
ionic -v
cordova -v

If Ionic command shows like this:

[INFO] The Ionic CLI has an update available (3.4.0 => 3.5.0)!

Then we have to update the Ionic CLI to the latest version. We can update it together with Cordova.

npm install -g ionic cordova

or

sudo npm install -g ionic cordova

Next, create new Ionic 3, Angular 4 and Cordova app by type this command.

ionic start ionic3-linkedin blank --cordova

It will automatically run npm install, so it will take minutes to complete. If there's a question like this:

Test and share your app on a device with the Ionic View app:
  http://view.ionic.io

? Link this app to your Ionic Dashboard to use tools like Ionic View? (Y/n) n

For now, choose 'n' because we will not use 'ionic.io' for now. Next, go to the newly created Ionic 3 project folder.

cd ionic3-linkedin

Open and edit file 'config.xml' from the root of the project folder then change widget id same as previously set up in the LinkedIn app.

<widget id="com.linkedin.ionic3" version="0.0.1" xmlns="http://www.w3.org/ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/1.0">

Now, run the app on the browser by type this command.

ionic serve --lab

The default browser will automatically open and it looks like this.

Ionic 3, Angular 4 and Cordova LinkedIn Authentication Tutorial - Ionic 3 Lab on The Browser

Stop the running Ionic app hold control key together with c (ctrl+c).


Add Ionic 3 Cordova Native Linkedin Plugin

Now, we have to install Ionic 3 Cordova Native Linkedin plugin. You can check that plugin is supported by Ionic Framework and Cordova at Ionic Native Docs. In the terminal or command line type this command.

ionic cordova plugin add cordova-plugin-linkedin --variable APP_ID=YOUR_APP_ID

Which 'YOUR_APP_ID' is the client ID of your Linkedin app that previously written after Linkedin setup. Then install the module by type this command.

npm install --save @ionic-native/linkedin

Next, open the file 'src/app/app.module.ts' then add this import.

import { LinkedIn } from '@ionic-native/linkedin';

Also, add to the providers' section in '@NgModule'. So it will look like this.

providers: [
  StatusBar,
  SplashScreen,
  {provide: ErrorHandler, useClass: IonicErrorHandler},
  LinkedIn
]

That is the basic setup for the plugin. Next, we will cover all feature or function in the plugin.


Create LinkedIn Login and Logout

We will create Linkedin login by add 'login with LinkedIn' button the current home page. Started with the controller, open and edit the file 'src/pages/home/home.ts' then add this import of the LinkedIn module.

import { LinkedIn } from '@ionic-native/linkedin';

Also, inject LinkedIn module to the constructor.

constructor(public navCtrl: NavController, private linkedin: LinkedIn) {}

Add variable below of class name.

scopes: LinkedInLoginScopes[] = ['r_basicprofile', 'r_emailaddress', 'rw_company_admin', 'w_share'];

Add new login function for login to LinkedIn.

login() {
  this.linkedin.login(this.scopes, true)
    .then(() => console.log('Logged in!'))
    .catch(e => console.log('Error logging in', e));
}

Now, we have to create a button for login to LinkedIn. Open and edit file 'src/pages/home/home.html' then add this HTML tags.

<ion-content padding>
  The world is your oyster.
  <p>
    If you get lost, the <a href="http://ionicframework.com/docs/v2">docs</a> will be your guide.
  </p>

  <h3>
    <button ion-button round outline (click)="login()">Login with&nbsp;<ion-icon name="logo-linkedin"></ion-icon></button>
  </h3>
</ion-content>

This time we have to run the app to make sure all configuration working properly. Using this plugin only working with the real device, so in the terminal or cmd run this command. Before it, make sure your device is connected to your computer.

ionic cordova run android

Ionic 3, Angular 4 and Cordova LinkedIn Authentication Tutorial - Ionic 3 with LinkedIn login button

Tap on Login with 'in' button. If it's working, it should open LinkedIn the app to get confirmation. Otherwise, this error will be shown on the chrome inspector.

Error logging in {
  "errorCode": "INVALID_REQUEST",
  "errorMessage": "either bundle id or package name \/ hash are invalid, unknown, malformed"
}

Tap 'OK' button from the LinkedIn app that open. If the login is a success, you will see in the Chrome inspector console the message 'Logged in!'. That's mean, our configuration is working.

To check if we the login is active or session is active, open and edit again 'home.ts' then add this variable below the previous variable.

isLoggedIn: boolean = false;

Then add function for checking active session inside 'ionViewDidAppear' built-in Ionic 3 method (Add this method if doesn't exist).

ionViewDidAppear() {
    this.linkedin.hasActiveSession().then((active) => {
        this.isLoggedIn = active;
    });
}

Also, we have to add the logout function.

logout() {
  this.linkedin.logout();
  this.isLoggedIn = false;
}

Edit function login and make it like this.

login() {
  this.linkedin.login(this.scopes, true)
    .then(() => this.isLoggedIn = true)
    .catch(e => console.log('Error logging in', e));
}

Next, edit again 'home.html' and replace all body content to be like this.

<ion-content padding>
  <h1>Ionic 3 LinkedIn Authentication</h1>

  <h3 *ngIf="isLoggedIn; else isLoggedOut">
    <button ion-button round outline (click)="logout()">Logout from&nbsp;<ion-icon name="logo-linkedin"></ion-icon></button>
  </h3>
  <ng-template #isLoggedOut>
    <h3>
      <button ion-button round outline (click)="login()">Login with&nbsp;<ion-icon name="logo-linkedin"></ion-icon></button>
    </h3>
  </ng-template>
</ion-content>

Now, run again on the device and see the difference.


Get ID, First Name and Last Name from LinkedIn

This plugin has a function to get the ID, First Name and Last Name from LinkedIn of the current logged in user. Open and edit 'home.ts' the add this variable for holding data.

selfData = { id:"", firstName:"", lastName:"" };

Create a new function to get data.

getSelfData() {
    this.linkedin.getRequest('people/~')
        .then(res => {
            this.selfData = res;
        })
        .catch(e => console.log(e));
}

Call that function on 'ionViewDidAppear' and 'login' function, so it will be called after current user logged in.

ionViewDidAppear() {
    this.linkedin.hasActiveSession().then((active) => {
        this.isLoggedIn = active;
        if(this.isLoggedIn === true) {
            this.getSelfData();
        }
    });
}

login() {
    this.linkedin.login(this.scopes, true)
        .then(() => {
            this.isLoggedIn = true;
            this.getSelfData();
        })
        .catch(e => console.log('Error logging in', e));
}

Now, we will display ID, first name and last name in the view. Edit 'home.html' then add these lines after 'isLoggedIn' if clause.

<h3 *ngIf="isLoggedIn===true">
    <ul>
        <li>ID: {{selfData.id}}</li>
        <li>First Name: {{selfData.firstName}}</li>
        <li>Last Name: {{selfData.lastName}}</li>
    </ul>
    <br>
    <button ion-button round outline (click)="logout()">Logout from&nbsp;<ion-icon name="logo-linkedin"></ion-icon></button>
</h3>

Run again the app on the device, then see what happens after login successfully. It should be like this.

Ionic 3, Angular 4 and Cordova LinkedIn Authentication Tutorial - Ionic 3 LinkedIn User Data


Share something on LinkedIn Profile

Another plugin function is post something to currently logged in user LinkedIn profile. We can test it using below function, edit 'home.ts' then add this function.

shareSomething() {
    const body = {
        comment: 'May I Share something on my profile?',
        visibility: {
            code: 'anyone'
        }
    };

    this.linkedin.postRequest('~/shares', body)
        .then(res => console.log(res))
        .catch(e => console.log(e));
}

Add a share button to the view before log out button. So, the complete content of the view should be like this.

<ion-content padding>
  <h1>Ionic 3 LinkedIn Authentication</h1>

  <h3 *ngIf="isLoggedIn===true">
    <ul>
      <li>ID: {{selfData.id}}</li>
      <li>First Name: {{selfData.firstName}}</li>
      <li>Last Name: {{selfData.lastName}}</li>
    </ul>
    <br>
    <button ion-button round outline (click)="shareSomething()">Share to&nbsp;<ion-icon name="logo-linkedin"></ion-icon></button>
    <br>
    <button ion-button round outline (click)="logout()">Logout from&nbsp;<ion-icon name="logo-linkedin"></ion-icon></button>
  </h3>
  <h3 *ngIf="isLoggedIn!==true">
    <button ion-button round outline (click)="login()">Login with&nbsp;<ion-icon name="logo-linkedin"></ion-icon></button>
  </h3>
</ion-content>

Re-run again and click the share button.

That it's for now, you see full source code on our GitHub.

We know that building beautifully designed Ionic apps from scratch can be frustrating and very time-consuming. Check Ionic 4 - Full Starter App and save development and design time. Android, iOS, and PWA, 100+ Screens and Components, the most complete and advance Ionic Template.

That just the basic. If you need more deep learning about Ionic, Angular, and Typescript, you can take the following cheap course:

Thanks!

Loading…