Introduction

In this tutorial we are going to show you - step by step - how to integrate Twitter Login to your Ionic Apps. This will enable an easy and elegant way for your users to login to your app.

Why adding Twitter Authentication into your app will benefit you and your users?

  • Improve conversions: Help people log into your app quickly without having to remember another username and password.
  • One login across every device: Make it easy for people to log in and access their info across multiple platforms and devices.
  • Build a trusted relationship: Give people control over the info they share with your app.
  • Access profile info: like picture, gender, age, name, without having to ask for it.

Authentication options

Authentication is a key component for your app, and there are some different approaches that you can take.

The handcrafted way (using your own API/Backend)

If you already have an API or backend that handles user authentication, or if you are one of those who like to have strict control over the backend implementation, then this may be your option.

Mobile apps require a different authentication strategy than web apps or websites. You don’t have sessions so you have to go with the token based authentication. For my clients production apps I use Strongloop. Basically is a platform that enables you to easily build custom API’s for your backend needs. It comes with token based authentication and an AngularJS SDK that works smoothly in your Ionic app. (You can read more about how easy is to manage users in this post “Managing users with StrongLoop”)

The BaaS way

If you don’t want to take care of your own infrastructure and backend implementation, then there are a few BaaS (Backend as a Service) options.

Firebase is a great service that will help you build your app’s backend with ease. (owned by Google). You can read the following tutorial to learn how to Add Firebase authentication to your Ionic App.

The guys from Ionic recently launched the Ionic Platform which is a BaaS solution with very useful services to build mobile apps. This platform offers cool features among push notifications and user authentication. We have made a tutorial to show you how to add Ionic Platform authentication into your Ionic app.

The Social way

You can chose to provide authentication using well known social networks such as Facebook, Instagram, Twitter, Google, etc. We think that nowadays this is the best way to login your users so we have created a set of tutorials to help you with this.

Each option has it’s benefits, and of course you can mix them together and have an even more complete solution and experience for your users. It’s very common to see different ways of authenticating users within an app.

Twitter Authentication

There are different ways to integrate Twitter authentication into your Ionic app. However, only the way covered in this post uses the native approach which uses Twitter app to perform the login instead of opening a popup requesting users to enter their credentials to login to Twitter before granting access to your app.

The way it works for hybrid apps to use native API’s and SDK’s is simple, you need a piece (typically a PhoneGap/Cordova plugin) that connects native API’s and SDK’s with the javascript environment where the hybrid apps run. In this case we are going to use a great cordova plugin to interact with the native google sdk.

We will use Twitter Connect Plugin to login with Twitter on iOS and Android. You will not only get the name of the user, but also stuff like their full name, followers, and picture.

Hands on!

Remember... you will need:

  • An Ionic app where you will integrate this login. You can either use a blank app, or an existing one.
  • Fabric API key
  • Register a Twitter App and get the Twitter Consumer Key and Twitter Consumer Secret
  • The Twitter Connect Plugin to interact with the native Twitter App.
Ad time!: If you are looking for a beautiful starter app with Ionic you must have a look at our beautiful mobile themes, templates & components developed for Ionic2.

This is how it will look like

iOS

Step 1: Get a Fabric API key

Using Twitter's Fabric SDK, you can enable Single Sign On with your Android and iOS apps.

To use Fabric, you will need to create an account. Apparently they have to authorize people manually, so it might be a while until your account is created.

To get the API key login to Fabric account and open https://fabric.io/kits/android/crashlytics/install

Step 2: Register your Twitter app

In this section I will help you creating your Twitter app in order to get the consumer key and consumer secret.

Step 3: Install Twitter Connect Plugin

After you have your Fabric API key it’s time to install the plugin into your app. Follow these steps to get this done:
  • Execute the following command on the terminal changing the variables with your own values:
    • Replace fabric_API_key with your FABRIC_KEY

    ionic cordova plugin add twitter-connect-plugin --variable FABRIC_KEY=fabric_API_key --save

    npm install --save @ionic-native/twitter-connect

Now you have to add the following lines before the closing </widget> tag in the config.xml file.

	<preference name="TwitterConsumerKey" value="<Your Twitter Consumer Key>"/>
	<preference name="TwitterConsumerSecret" value="<Your Twitter Consumer Secret>"/>

What we have done so far:

  • Created an Ionic app (or used a existing one)
  • Created a Fabric Account
  • Created a Twitter app (or used a existing one)
  • Twitter Connect Plugin installed into your Ionic app

Step 4: Adding Login/Logout functionality

Now we will go straight to the code so open your Ionic App with your preferred code editor. Personally I use and recommend atom.


We don't want to ask users to log in each time they open the app because it would be annoying. To solve this we are going to use NativeStorage to save the user data the first time they log in.

NativeStorage

NativeStorage is a Cordova plugin which provides persistent storage of primitives native in Android, iOS and Windows. It's created because of the non-persistent property of LocalStorage in the WebView of Android and iOS. In iOS stored data from LocalStorage can be removed by the OS, when running out of memory.

To install this plugin just run the following command in your ionic project:

$ ionic cordova plugin add cordova-plugin-nativestorage --save

$ npm install --save @ionic-native/native-storage

We added a check in the platform.ready() in app.component.ts to check if the user is already logged in.

constructor(
	platform: Platform,
	public nativeStorage: NativeStorage,
	public statusBar: StatusBar,
	public splashScreen: SplashScreen
) {
  platform.ready().then(() => {
    // Here we will check if the user is already logged in
    // because we don't want to ask users to log in each time they open the app
    let env = this;
    this.nativeStorage.getItem('twitter_user')
    .then( function (data) {
      // user is previously logged and we have his data
      // we will let him access the app
      env.nav.push(UserPage);
      env.plashscreen.hide();
    }, function (error) {
      //we don't have the user data so we will ask him to log in
      env.nav.push(LoginPage);
      env.splashscreen.hide();
    });

    this.statusBar.styleDefault();
  });
}

Login

The best way to show you how to add Login functionality is with a real example of the code, here you can see some Typescript code that handles the Twitter login for your app.

import { Component } from '@angular/core';
import { NavController, LoadingController } from 'ionic-angular';
import { UserPage } from '../user/user';
import { TwitterConnect } from '@ionic-native/twitter-connect';
import { NativeStorage } from '@ionic-native/native-storage';


@Component({
  selector: 'page-login',
  templateUrl: 'login.html',
})
export class LoginPage {

  constructor(public navCtrl: NavController,
	public navCtrl: NavController,
	public loadingCtrl: LoadingController,
	public tw: TwitterConnect,
	public nativeStorage: NativeStorage)
 {}

  doTwLogin(){
    let nav = this.navCtrl;
    let loading = this.loadingCtrl.create({
      content: 'Please wait...'
    });

    loading.present();
		let env = this;
    //Request for login
    this.tw.login().then(function(result) {
      //Get user data
      env.tw.showUser().then(function(user){
        //Save the user data in NativeStorage
        env.nativeStorage.setItem('twitter_user',
        {
          name: user.name,
          userName: user.screen_name,
          followers: user.followers_count,
          picture: user.profile_image_url_https
        }).then(function() {
          nav.push(UserPage);
        })
      }, function(error){
        loading.dismiss();
      });
    });
  }
}

Logout

The following is the necessary code for the Twitter Log out:

import { Component } from '@angular/core';
import { NavController, LoadingController } from 'ionic-angular';
import { LoginPage } from '../login/login';
import { UserModel } from './user.model';
import { TwitterConnect } from '@ionic-native/twitter-connect';
import { NativeStorage } from '@ionic-native/native-storage';


@Component({
  selector: 'page-user',
  templateUrl: 'user.html'
})

export class UserPage {

  user: UserModel = new UserModel();

  constructor(
	public navCtrl: NavController,
  	public loadingCtrl: LoadingController,
  	public tw: TwitterConnect,
  	public nativeStorage: NativeStorage)
 {}

  ionViewCanEnter(){
    let env = this;
    let loading = this.loadingCtrl.create({
      content: 'Please wait...'
    });

    loading.present();

    this.nativeStorage.getItem('twitter_user')
    .then(function (data){
      env.user = {
        name: data.name,
        userName: data.userName,
        picture: data.picture,
        followers: data.followers
      };
      loading.dismiss();
    }, function(error){
      console.log(error);
      loading.dismiss();
    });
  }

  doTwLogout(){
    let nav = this.navCtrl;
		let env = this;
    this.tw.logout().then(function(response)
    {
      env.nativeStorage.remove('twitter_user');
      nav.push(LoginPage);
    }, function (error) {
      console.log(error);
    });
  }
}

What we have done so far:

  • At this point you should have an Ionic app with Twitter login and logout functionalities working.

Next Steps

After having Twitter authentication working in your Ionic App you can focus on:

As you know we also sell beautiful mobile themes, templates and components that you may find super useful as they save you hours of development, time and effort, while giving your projects a great design from scratch.

Why don’t you give a chance to these Ionic templates and apply this new knowledge?