Last update on Sunday, June 2nd 2019

Adding Twitter Authentication with Firebase in Ionic

The OAuth system allows us to skip the registration step and allows a user to directly access the application using a social media account.
In this tutorial we mix together Firebase and Twitter's Authentication in an Ionic mobile application.
Just like the previous tutorial on Google OAuth, this process is done in two steps:

  1. The authentication on Twitter's side
  2. Acquiring a token and secret ID from this first step and passing it to Firebase

Setting up Firebase and Twitter projects

Let's get into the (magnificent) Web Interfaces setup.
The first step is acquiring the callback url from Firebase and enabling the service in the Authentication section:

ionic twitter firebase oauth enable

Here is our callback url:

ionic twitter firebase oauth get callbkack url

The twitter application can now be created there:

ionic twitter firebase oauth create app

Like this:

ionic twitter firebase oauth create app

For iOS development an additional callback url is also required: twittersdk://

Entering inside the newly created app now:

ionic twitter firebase oauth get ids

The important API IDs (or keys) are here.

Next step, going back to Firebase to add those IDs:

ionic twitter firebase oauth add ids

We are almost done with the boring exciting interface configurations.
In order to use the Ionic Native Twitter Connect plugin, we need one last ID from a service named Fabric.

An account is required there.
After login in, acquiring the API key is tricky, there is no "API keys" section, however there is one tutorial page where the API key is used in a code snippet there:

ionic twitter firebase oauth fabric key

Ok let's fire up our IDEs and code that app!

Twitter Communication

As usual we start with the project creation and Ionic & Cordova plugins installation:

ionic start ionic-firebase-twitter-oauth blank
ionic cordova plugin add twitter-connect-plugin
 --variable FABRIC_KEY=a1cb272c54f3604b3e66f5b8f4602e6182289dff
npm install --save @ionic-native/twitter-connect

Right off the bat, the IDs are used. The Fabric key for installing the Ionic Native Twitter Connect plugin and the Twitter API keys are added to the config.xml file:

<preference name="TwitterConsumerKey" 
            value="ZhGJh5KCmjJo5yCSJ2IyklEvd" />
<preference name="TwitterConsumerSecret"
            value="XAPP8JaZicdtAiBFG2urJEhrsLqadb2id7VBgKuAF1EevJhOZC" />

The Twitter Connect plugin is then added to the home.module.ts file as a Provider:

import { TwitterConnect } from '@ionic-native/twitter-connect/ngx';
...

@NgModule({
  ...
  providers: [
     ...
    TwitterConnect

  ]
})
export class HomeModule {}

The home.page.html file:

<ion-header>
  <ion-toolbar>
    <ion-title>
      Ionic Twitter Firebase login
    </ion-title>
  </ion-toolbar>
</ion-header>

<ion-content padding>

  <div text-center>
    <ion-button (click)="login()">
      Login
    </ion-button>
  </div>

  <ion-item *ngIf="user">
    <h2>{{user.displayName}}</h2>
    <ion-thumbnail item-end>
      <img src="{{user.photoURL}}">
    </ion-thumbnail>
  </ion-item>

</ion-content>

One simple button to login and an <ion-item>.
The <ion-item> will show the user's name and picture, but only if the user exists.

The rest of the code is in the home.page.ts file:

import { TwitterConnect } from '@ionic-native/twitter-connect/ngx';
...

export class HomePage {

  constructor(public twitterConnect: TwitterConnect) { }

  login() {
    this.twitterConnect.login().then(this.onSuccess, this.onError);
  }

  onSuccess(response) {
    console.log('response', response);
    console.log(response.userName);
    console.log(response.userId);
    console.log(response.secret);
    console.log(response.token);
  }

  onError(error) {
    console.log('error', error);
  }
}

The Ionic Native TwitterConnect plugin is imported and injected into a twitterConnect property.
The login method uses twitterConnect's login method and handle the success and errors. If Twitter is nice to us, we should receive an object that has the secret ID and the token.
Those information will be used by Firebase in AngularFire.

Last Stop: Firebase

Let's install the AngularFire2 library:

npm install firebase angularfire2 --save

And set it up in the home.module.ts file:

import { AngularFireModule } from 'angularfire2';
import { AngularFireAuthModule, AngularFireAuth } from 'angularfire2/auth';

import { environment } from '../environments/environment';
...

@NgModule({
  ...
  imports: [
    ...
    AngularFireModule.initializeApp(environment.firebase),
    AngularFireAuthModule
  ],
  providers: [
    ...,
    TwitterConnect,
    AngularFireAuth
  ]
})
export class HomeModule {}

As we have seen in a previous tutorial, the AngularFire and AngularFireAuth modules are imported with the Firebase configuration file named environment.ts.
The AngularFireAuth Service is then added as Provider alongside the TwitterConnect Service.

Back to the home.page.ts_file:

import { AngularFireAuth } from 'angularfire2/auth';
import * as firebase from 'firebase/app';
...
@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss'],
})
export class HomePage {
  user;

  constructor(public navCtrl: NavController,
    public twitterConnect: TwitterConnect,
    public afAuth: AngularFireAuth,
    public platform: Platform) {
  }
  ...
}

The initialization part is different now, we need to add the AngularFireAuth Provider and also import the whole firebase library to stock it in a firebase variable.
A new user property will be set later when the data come from Firebase through the updated onSuccess method:

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

  this.afAuth.auth
    .signInWithCredential(twitterCredential)
    .then(res => {
      this.user = res.user;
    })
    .catch(error => console.log("error", error));
};

This time we do some work with the response we received from Twitter.
The token and secret keys are used to create the Twitter credential. This information will be used to sign in the user on Firebase‘s side with the signInWithCredential method.
Once this is successfully done, we receive our Firebase user.

Here is the final result:

ionic twitter firebase oauth result

Conclusion

Allowing users to login without using their password is awesome (I generally forget mines and have to retrieve it by mail every time).
In this case, this process is controlled by two entities: Twitter and Firebase.
Both have their own Web Interfaces where the IDs are available. Those IDs or API keys allow us to link our applications to their services. First connecting to Twitter then Firebase using Twitter’s credential.

If you liked this tutorial, you can learn more on Firebase’s database, storage, cloud functions and basic authentication.

Using Firebase and AngularFire2 Basic Authentication in an Ionic application

Learn how to
quickly build a B...
...

Creating an Ionic PWA with Firebase Offline and Service Workers

Learn how to
create your first ...
...

Using Firebase and AngularFire2 in an Ionic Real-Time TODO application

Learn how to use
Firebase RealTi...
...

Stay up to date


Join over 4000 other developers who already receive my tutorials and their source code out of the oven with other free JavaScript courses and an Angular cheatsheet!
Designed by Jaqsdesign