Ionic twitter login => A Step-by-step guide

First Published: 8 March 2017
Updated on: 24 September 2018

Have you tried to get Ionic Twitter login working with Firebase? There was a change when Firebase updated to V3 that made all the cool sign-in with pop-up and redirection stop working with Cordova apps. It sucked!

But then I realized something, yeah, it sucked for us as developers, but it pushed us to find a better way for our users, and it was to find the native plugins.

Why is it better for our users? Because when you used ionic twitter login in the previous version it had a pop-up to authorize the app, that pop-up was usually a browser one, and the user had to enter their twitter credentials half of the time. And that really sucks (I’m looking at you Instagram!

Instagram Login

That really sucks, why would I want to enter my credentials, can’t they just have a cool native pop-up so I can click and authorize it?

We’re going to be using the twitter-connect plugin and connecting to twitter using the Fabric SDK, that way, we can give a native experience to our users, instead of making our users think/do too much.

In this post, you’ll learn:

  • How to set up your Fabric account.
  • How to set up the Twitter Connect plugin (from Ionic Native)
  • How to use the plugin to get the login token.
  • Use those token credentials to sign your user into Firebase.

You’ll be able to give your users a better experience, similar to the picture below:

Twitter Login Screen

Ready to get started?

Make sure to get the code directly from Github so you can follow along with the post: https://github.com/javebratt/Ionic-Twitter-Login.

Ionic Twitter Login

We’re going to break down the process in 6 steps:

  • Step #1: Set up your Fabric Account.
  • Step #2: Get your Fabric API Key.
  • Step #3: Create your app in Fabric.
  • Step #4: Install the Twitter Connect Plugin
  • Step #5: Enable Twitter Authentication in Firebase.
  • Step #6: Write the code to get the token from Twitter and sign the user in.

I think that intro was too long, so let’s get busy.

Step #1: Set up your Fabric Account

How many times have I said something sucked in this post? This is going to be another one, this process sucks! :P

There’s a lot of work on setting up your fabric account, including running Android Studio (or Xcode) installing plugins, and running a native app.

In the next few lines I’ll do my best to explain it so you don’t have to bang your head against the keyboard (like I did).

The first thing you’ll do is go to Fabric’s website and create an account

Get Fabric Account

After you signup, they’ll send you a confirmation email so you can get started, go to your email and click on the link they sent you.

It will take you to a page where you can start working with Fabric, you’ll add a team name, and then it will ask you what platform you’re developing for, this is where things get tricky.

fabric select platform

You can either select iOS or Android, one little advise, choose the one where you have the SDK and native IDE up to date, so if your Android Studio installation and Android SDK are up to date, go ahead and pick android, if not, then pick iOS.

When you pick the platform you’ll go through an on-boarding process (yup, they actually think this is good), just read through every single message and follow the instructions step by step

Personalize Fabric Android

But basically, you need to install Fabric’s plugin in your IDE, then install the Twitter SDK into your app through the plugin, the plugin will show you how to install it, it even has a one-click install that adds everything (at least on Android it does).

Once everything is installed, you need to build and run the app, once you do, it will send a signal to Fabric letting them know that you have successfully installed and ran the SDK, which will let you pass this “pending” page:

Fabric Pending Account

If it doesn’t happen automatically, feel free to comment and I’ll help you debug.

Step #2: Get your Fabric API key

I don’t know why, but there’s no easy way to get this, like, I would expect you could go into settings and copy your API key, but no, that’s not what they wanted I guess.

Thankfully, Manifest Web Design, the awesome people that wrote the Twitter Connect Plugin already knew this and they had instructions on how to get your API key.

Fabric API keys

Easy, right? :P

Step #3: Create your Fabric APP

It’s time to create the app we’ll be using to ask for the user’s permissions, this on the easier side of things, all you have to do is go to https://fabric.io/settings/apps and click the “ADD” button, it will ask you for some information and you’ll be able to create the app.

The app will have some information on it, you’ll need to copy the CONSUMER KEY and the CONSUMER SECRET, since we’ll need them later for the plugin setup.

Step #4: Install the Twitter Connect Plugin

Now it’s time to install the Twitter Connect Plugin, for that we first need to have an Ionic Framework app created, if you don’t know how to create an Ionic app and initialize Firebase then first read this post and come back to this after you’re done.

Now that your app is created, open your terminal (you should be inside your app’s folder) and install the twitter connect plugin:

ionic plugin add twitter-connect-plugin --variable FABRIC_KEY=<FabricAPIKey>
npm install --save @ionic-native/twitter-connect

Remember to change <FabricAPIKey> with your own API key (the one we got in Step #2).

Once the plugin is installed, you’ll need to do some config, go ahead and open the config.xml file that’s in the project root, and right before the closing </widget> tag, add this:

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

Remember to change those values with the CONSUMER KEY and the CONSUMER SECRET we got in Step #3 when we created the app in Fabric.

We need to declare the twitter-connect package as a provider in app.module.ts now:

import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';
import { TwitterConnect } from '@ionic-native/twitter-connect';

@NgModule({
  ...,
  ...,
  ...,
  providers: [
    {provide: ErrorHandler, useClass: IonicErrorHandler},
    StatusBar,
    SplashScreen,
    TwitterConnect
  ]
})
export class AppModule {}

That’s it, everything in your app is set up and ready to be used.

Step #5: Enable Twitter Authentication in Firebase.

Now you need to tell your Firebase app to allow users to Sign-In with Twitter, for that go to your Firebase Console

Choose your app and inside the Authentication Tab go to “Sign-In Method” and enable Twitter, it’s going to ask you for an API Key and Secret, you’ll use the same you just used, the ones for the app you created in Fabric.

firebase enable twitter login

Step #6: Write the code to get the token from Twitter and sign the user in

We can finally start coding now :)

The first thing we’ll do is create a button so our user can log-in, so go ahead and open home.html and remove the placeholder content, then add a button:

<ion-content padding>
  <button
    ion-button
    block
    color="primary"
    (click)="twLogin()"
    *ngIf="!userProfile"
  >
    <ion-icon name="logo-twitter"></ion-icon>
    Login with Twitter
  </button>
</ion-content>

The button is calling a function that we’ll create in the Class that will handle the login part, it also has an ngIf tag, that makes sure you only see the button if you’re logged out (we’ll create that logic later).

If the user is logged-in, we want to show the user’s profile picture, twitter name, and full name.

<ion-content padding>
  <button
    ion-button
    block
    color="primary"
    (click)="twLogin()"
    *ngIf="!userProfile"
  >
    <ion-icon name="logo-twitter"></ion-icon>
    Login with Twitter
  </button>

  <ion-item *ngIf="userProfile">
    <ion-avatar item-left>
      <img [src]="userProfile.photoURL" />
    </ion-avatar>
    <h2>{{ userProfile.displayName }}</h2>
    <h3>{{ userProfile.twName }}</h3>
  </ion-item>
</ion-content>

By the end, that page will look something like this:

Ionic Twitter Login

Now that we have that part covered, then it’s time to import everything we’ll need into home.ts

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { TwitterConnect } from '@ionic-native/twitter-connect';
import firebase from 'firebase';
  • We’re importing TwitterConnect because that’s the ionic native package to handle the plugin.
  • And we’re importing Firebase so we can sign-in our users.

Then, right before the constructor, we need to add one variable:

userProfile: any = null;

The userProfile will hold the information we want to show about the user.

Now initialize the zone variable in the constructor and inject TwitterConnect

constructor(public navCtrl: NavController, private twitter: TwitterConnect) {}

It’s time to move to our login function, we’re going to create the function and add the login functionality for twitter, go ahead and add this to your code:

twLogin(): void {
  this.twitter.login().then( response => {
    console.log(response);
  }, error => {
    console.log("Error connecting to twitter: ", error);
  });
}

Right there you’ll get all the twitter functionality, go ahead and run it in a phone, you should see the blue login button, when you click it you’ll get a screen like this:

ionic twitter login screen

If you’re inspecting the device, you’ll notice it logs the response to the console, the response looks something like this:

{
  userName: 'myuser',
  userId: '12358102',
  secret: 'tokenSecret'
  token: 'accessTokenHere'
}

We need to pass now that token and secret to Firebase so our user can log into our application.

For that first, create a credential object using the TwitterAuthProvider method, and then pass that object to Firebase:

twLogin(): void {
  this.twitter.login().then( response => {
    const twitterCredential = firebase.auth.TwitterAuthProvider
        .credential(response.token, response.secret);

    firebase.auth().signInWithCredential(twitterCredential)
    .then( userProfile => {});
  }, error => {
    console.log("Error connecting to twitter: ", error);
  });
}

We’re using

const twitterCredential = firebase.auth.TwitterAuthProvider.credential(
  response.token,
  response.secret
);

To create a credential object and then pass it to the signInWithCredential Firebase method, then we just need to handle the return of that function, we’ll just add the response to the this.userProfile variable so we can use it in our HTML

twLogin(): void {
  this.twitter.login().then( response => {
    const twitterCredential = firebase.auth.TwitterAuthProvider
      .credential(response.token, response.secret);

    firebase.auth().signInWithCredential(twitterCredential)
    .then( userProfile => {
      this.userProfile = userProfile;
      this.userProfile.twName = response.userName;
      console.log(this.userProfile);
    }, error => {
      console.log(error);
    });
  }, error => {
    console.log("Error connecting to twitter: ", error);
  });
}

We’re also adding this.userProfile.twName = response.userName; because the firebase authentication object doesn’t have that information for us.

And that’s it, you now have a fully working authentication system using Twitter and Firebase :)

Next Steps

If you have any questions don’t forget you can always leave a comment below.

If you want to take a deeper dive on Ionic + Firestore you should go through my FREE course: Build your first Firestore powered Ionic app.