How can I login with multiple social services with Firebase?

AuthenticationFacebook AuthenticationFirebaseFirebase Security

Authentication Problem Overview


I want users to be able to authenticate to my Firebase application using multiple different auth providers, such as Facebook, Twitter, or Github. Once authenticated, I want users to have access to the same account no matter which auth method they used.

In other words, I want to merge multiple auth methods into a single account within my app. How can I do this in a Firebase app?

Authentication Solutions


Solution 1 - Authentication


Update (20160521): Firebase just released a major update to its Firebase Authentication product, which now allows a single user to link accounts from the various supported providers. To find out more about this feature, read the documentation for iOS, Web and Android. The answer below is left for historical reasons.


The core Firebase service provides several methods for authentication: https://www.firebase.com/docs/security/authentication.html

At its core, Firebase uses secure JWT tokens for authentication. Anything that results in the production of a JWT token (such as using a JWT library on your own server) will work to authenticate your users to Firebase, so you have complete control over the authentication process.

Firebase provides a service called Firebase Simple Login that is one way to generate these tokens (this provides our Facebook, Twitter, etc auth). It's intended for common auth scenarios so that you can get up and running quickly with no server, but it is not the only way to authenticate, and isn't intended to be a comprehensive solution. 

Here's one approach for allowing login with multiple providers using Firebase Simple Login:

  1. Store one canonical user identifier for each user, and a mapping for each provider-specific identifier to that one canonical id.
  2. Update your security rules to match any of the credentials on a given user account, instead of just one.

In practice, the security rules might look like this, assuming you want to enable both Twitter and Facebook authentication (or allow a user to create an account with one and then later add the other):

{
  "users": {
    "$userid": {
      // Require the user to be logged in, and make sure their current credentials
      // match at least one of the credentials listed below, unless we're creating
      // a new account from scratch.
      ".write": "auth != null && 
        (data.val() === null || 
        (auth.provider === 'facebook' && auth.id === data.child('facebook/id').val() || 
        (auth.provider === 'twitter' && auth.id === data.child('twitter/id').val()))"
    }
  },
  "user-mappings": {
    // Only allow users to read the user id mapping for their own account.
    "facebook": {
      "$fbuid": {
        ".read": "auth != null && auth.provider === 'facebook' && auth.id === $fbuid",
        ".write": "auth != null && 
          (data.val() == null || 
          root.child('users').child(data.val()).child('facebook-id').val() == auth.id)"
      }
    },
    "twitter": {
      "$twuid": {
        ".read": "auth != null && auth.provider === 'twitter' && auth.id === $twuid",
        ".write": "auth != null && 
          (data.val() == null || 
          root.child('users').child(data.val()).child('twitter-id').val() == auth.id)"
      }
    }
  }
}

In this example, you store one global user id (which can be anything of your choosing) and maintain mapping between Facebook, Twitter, etc. authentication mechanisms to the primary user record. Upon login for each user, you'll fetch the primary user record from the user-mappings, and use that id as the primary store of user data and actions. The above also restricts and validates the data in user-mappings so that it can only be written to by the proper user who already has the same Facebook, Twitter, etc. user id under /users/$userid/(facebook-id|twitter-id|etc-id).

This method will let you get up and running quickly. However, if you have a complicated use case and want complete control over the auth experience, you can run your own auth code on your own servers. There are many helpful open source libraries you can use to do this, such as everyauth and passport.

You can also authenticate using 3rd party auth providers. For example, you can use Singly, which has a huge variety of integrations out-of-the-box without you needing to write any server-side code.

Solution 2 - Authentication

I know this post exists for months but when I faced this problem, it took lot of my time to make the code more flexible. Base on Andrew code above, I tweaked the code a little.

Sample data store:

userMappings
|---facebook:777
|   |---user:"123"
|---twitter:888
    |---user:"123"
users
|---123
    |---userMappings
        |---facebook: "facebook:777"
        |---twitter: "twitter:888"

Security rules:

"userMappings": {
  "$login_id": {
    ".read": "$login_id === auth.uid",
    ".write": "auth!== null && (data.val() === null || $login_id === auth.uid)"
  }
},

"users": {
  "$user_id": {
    ".read": "data.child('userMappings/'+auth.provider).val()===auth.uid",
    ".write": "auth!= null && (data.val() === null || data.child('userMappings/'+auth.provider).val()===auth.uid)"
  }
}

So userMappings is still the first information we look up when login by Facebook, Twitter.... the userMappings' user will point to the main account in users. So after login by Facebook or Twitter, we can look up the main user account. In users we keep list of userMapping that can access to its data.

When create new user, we have to create an account in users first. The id for user in users could be anything we want. This is flexible because we can provide more login method like Google, Github without adding more security rule.

Solution 3 - Authentication

I've just created an angularfire decorator to handle this for us: [angularfire-multi-auth][1]

[1]: https://github.com/douglascorrea/angularfire-multi-auth "angularfire-multi-auth"

Solution 4 - Authentication

I've spent quite some time thinking in a good solution, and IMHO to be able to register from any provider is just confusing. In my front end I always ask for a email registration, so a user logging with facebook and google+, for example, would be logged as the same user when he informs his email.

This way, the Sample Data proposed by Kuma don't need to duplicate the userMappings.

Sample Data Store:

userMappings
|---facebook:777
|   |---user:"123"
|---twitter:888
    |---user:"123"
users
|---123
    |---user data

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAndrew LeeView Question on Stackoverflow
Solution 1 - AuthenticationAndrew LeeView Answer on Stackoverflow
Solution 2 - AuthenticationKumaView Answer on Stackoverflow
Solution 3 - AuthenticationDouglas CorreaView Answer on Stackoverflow
Solution 4 - AuthenticationJp_View Answer on Stackoverflow