The Official Ionic Blog

Build amazing native and progressive web apps with HTML5

firebase-ionic-user-authentication

Firebase has become one of the most popular backend solutions for modern apps. With SDKs for almost every platform you can think of, it provides a real-time database that allows you to keep all your users in sync.

Firebase also has awesome authentication APIs that make adding social logins incredibly simple. If you don’t have a Firebase account, you can sign up free here. Let’s look at how we can add GitHub authentication to an existing app with Firebase and Ionic.

Setting up authentication in Firebase

Screen Shot 2015-06-30 at 11.06.57 AM

With a Firebase app already created, let’s navigate to the Login & Auth section of our Firebase app dashboard and enable GitHub authentication. Now we need keys from Github, so let’s create our app there and get our keys.

Screen Shot 2015-06-30 at 11.24.41 AM

From here, we can create a new GitHub application. We’ll need to provide a unique application name, as well as a homepage URL (which can be your app’s landing page, support page, etc.). We also need to enter an Authorization callback URL, which will allow GitHub to properly communicate with Firebase. We’ll set this to https://auth.firebase.com/v2/<YOUR-FIREBASE-APP>/auth/github/callback. Be sure to change <YOUR-FIREBASE-APP> to your app’s name.

Once the GitHub app is created, we’ll take a client ID and a client secret and paste them into the GitHub authentication section in our Firebase app dashboard. From there, all the backend work is done, and we can start building our Ionic app.

Building out the app

Let’s create a blank Ionic app. Then we’ll add AngularFire/Firebase from bower and Cordova’s InAppBrowser plugin.

$ ionic start myApp blank && cd myApp
$ ionic plugin add cordova-plugin-inappbrowser
$ ionic add angularfire

We’ll add Firebase and AngularFire to the index.html.

<script src="lib/firebase/firebase.js"></script>
<script src="lib/angularfire/dist/angularfire.min.js"></script>

Then, we’ll inject Firebase as a dependency of our app.

angular.module('starter', ['ionic', 'firebase'])

First, let’s create a factory to handle authentication.

  .factory('Auth', function($firebaseAuth) {
    var endPoint = <YOUR_FIREBASE_URL> ;
    var usersRef = new Firebase(endPoint);
    return $firebaseAuth(usersRef);
  })

Again, replace <YOUR_FIREBASE_URL> with the URL to your Firebase. From here, we can create our controller and log our users in.

.controller('AppCtrl', function($scope, Auth) {
  $scope.login = function(authMethod) {
    Auth.$authWithOAuthRedirect(authMethod).then(function(authData) {
    }).catch(function(error) {
      if (error.code === 'TRANSPORT_UNAVAILABLE') {
        Auth.$authWithOAuthPopup(authMethod).then(function(authData) {
        });
      } else {
        console.log(error);
      }
    });
  };
})

Auth.$authWithOAuthRedirect will attempt to authenticate using redirects. This is the normal and expected way to handle authentication, but on emulators, this method may fail because it might not support redirects. We’ll handle this by calling Auth.$authWithOAuthPopup if there is an error. Since we installed the InAppBrowser plugin, AngularFire will use the plugin to handle login. Now, let’s create the UI.

We’ll create a simple button that logs the user in:

<ion-pane ng-controller="AppCtrl">
  <ion-content>
    <button class="button button-royal icon ion-social-github" ng-click="login('github')"></button>
  </ion-content>
</ion-pane>

Now, our button will call the login function and pass in the string of ‘github’ to be used in our authentication. We’ll add some more code to our controller, to see the data of the user once they are logged in:

  Auth.$onAuth(function(authData) {
    if (authData === null) {
      console.log('Not logged in yet');
    } else {
      console.log('Logged in as', authData.uid);
    }
    // This will display the user's name in our view
    $scope.authData = authData;
  });

This uses AngularFire’s $onAuth method to set some scope data once we’re successfully authenticated. We can display this data by displaying a few extra lines of markup to our view:

    <div ng-if="authData.github" class="list card">
      <div class="item item-avatar">
        <img ng-src="{{authData.github.cachedUserProfile.avatar_url}}" alt="">
        <h2>{{authData.github.displayName}}</h2>
        <p>{{authData.github.username}}</p>
        <p>Github</p>
      </div>
    </div>

Now we can see the user’s profile picture, username, and displayed name. We’ve now added user authentication to our app in just a few lines of code!

Parting words

This method of handling authentication can be used for more than just GitHub. Firebase can also handle user authentication with Facebook, Twitter, Google, and even anonymous users. A sample project can be found here.

For more information, make sure to check out these resources:

  • http://caravanaweb.com.br juarezpaf

    Really nice Firebase + Ionic intro. I started to create content related to this, my first presentation is available here http://www.slideshare.net/juarezpaf/firebase-adventures-real-time-platform-for-your-apps
    Going to update my presentation with this tutorial. Keep rocking guys. /o/

  • http://www.hospity.com Hospity

    This is Great Wonderful Coding Technique.. awesome ideas Thanks..

    Web Development India

  • Amol

    Any resources/tutorials on using custom auth? Having a hard time figuring this out 🙁

  • Ramadhevi Rk

    suppose if I use firebase for integrating facebook, will that use browser facebook or native facebook app on mobile?

  • C.k

    I have some confuse about wondering does this social login plugin support user login by using account has login in social mobile app (facebook, gmail …) so this mean just open dialog ACCEPT then not require user need type login info (username/email, password) again.

  • Uri Naor

    I re-blogged your post in our company blog http://blog.datasol.us/ionic-social-authentication/
    Please let me know if thats cool with you , great post Uri

  • Tyrone

    In case you are planning on using Facebook login:

    I strongly advice users not to use the inappbrowser plugin as described by this article.

    Instead, use the https://github.com/Wizcorp/phonegap-facebook-plugin cordova plugin.

    Very easy to combine with Firebase, example explained here: http://stackoverflow.com/questions/26369551/firebase-how-to-authenticate-user-through-native-facebook-app

    This will result in a much smoother user experience as it uses the native Facebook app, and reverts back to browser in case Facebook app is not installed.

  • Bart van der Laan

    I’m using firebase and ionic for a while now. The combination is awesome. Denormalized data can be though sometimes though.

  • Wes A. Haque

    I’m using the email/password login system but I have a separate collection in firebase that holds additional data for every email address. I would like to log in and then pull in the extra data corresponding to that email address, I was wondering if any one could make a tutorial for this specific scenario. Or if someone could direct me to a similar solution online. Thanks.

  • Blusec Blusec

    I get this error when the popup box comes up

    Given URL is not allowed by the Application configuration: One or more of the given URLs is not allowed by the App’s settings. It must match the Website URL or Canvas URL, or the domain must be a subdomain of one of the App’s domains.

  • Scott

    Wow, great article. I was finally able to get social logins working with Ionic/Firebase on an Android. However, because there are so many different ways of testing/emulating Ionic apps, I found that it doesn’t work in all cases. The one that concerns me the most, is that I can’t get the Ionic View version working on my iPad. It seems to redirect to the login screen for the various providers (Facebook, Google, Twitter, and Github); but after logging in, it goes back to a blank screen, and never comes back. I’d really like to figure out how to get this to work, as I’m developing on a PC, and can only use Ionic View to show my apps on apple devices.

    Also, in Ionic serve (browser testing), I need to do a refresh after logging into the provider. Not a big deal; but a little annoying. Finally, when I use the new ionic serve –lab, when it tries to redirect to the provider page, it says Content can’t be shown in a frame. Unfortunately, it seems that the providers are setting the X-Frame-Options tag in the headers to DENY. Not sure if there is a way around this.

    • Jameesh Moidunny

      i am trying to add login using the same tutorial, and i am getting a blank page after login. I find that u are also had the same issue. Can you please let me know how you resolve this

      • Scott

        I’ve been able to get the user login working for all cases except running on Ionic view with an apple device. For my login function, I used the Firebase function: $authWithPassword, instead of $authWithOAuthPopup, used in this article. For a full working example see this github repositiory: https://github.com/scottnakada/UserAuth. It has samples of user authorization working in a web app, and Ionic app. For the apple app, I tested for the device running the app, and disabled login using social media if it was running iOS, since I wasn’t able to get that working.

  • Sergent Danny

    Hello Guys , this is a great tutorial , but is there any way to make a social login into the ionic app using social accounts from AndroidAccountsManager? I mean is not that usefull using inappbrowser…

  • lliccien

    Excellent Tutorial

    I want to know how I define the function Logout()

  • http://nicholls.azurewebsites.net/ Juan David Nicholls

    Firebase 3.2 shows an error: Uncaught ReferenceError: Firebase is not defined

  • iriekun

    can you update tutorial with firebase v3?