Firebase Social Login With React Native


(Skcript Bot) #1

Firebase is known for it’s simple setup to enable social logins, but when it comes to building an app with React Native and Firebase, setting up the social login is such a pain. This is mainly because we’ve got to use the JS SDK which is built for the web environment. But the problem is that you can use the social login functions as it won’t work outside the browser environment. In such cases, we’ll be following a different strategy which I’ll be explaining in this article.

Basic Requirements

  • React Native Project with Firebase Setup - Check this
  • Social Login Keys

The Strategy

Here since the Firebase web SDK’s functions for social login doesn’t work outside the browser environment, we’ll be using third-party libraries to first authenticate the social accounts and to get an access token for each of the corresponding networks.

Once we get the access token to a platform, we’ll then pass it to the Firebase library function.

How it works

For setting up the authentication part we’ll be needing three React Native Libraries that help you get the access token of the user for each corresponding platform. I’ve used the following libraries and they worked pretty well for me.

Once you install these libraries it injects the native code that triggers the social logins either directly from the install apps or from the browser.

Setting Up Twitter Login

For configuring the Twitter login you need the keys which I hope you already have. Now import the library like below.

const { RNTwitterSignIn } = NativeModules;

And once you import you can access the login function and get the access token like below.

function twitterLogin() {
  RNTwitterSignIn.init(<--CONSUMER_KEY-->, <--CONSUMER_SECRET-->);
  RNTwitterSignIn.logIn()
                 .then(function(loginData){
                    var accessToken = Firebase.auth
                                              .TwitterAuthProvider
                                              .credential(
                                                loginData.authToken,
                                                loginData.authTokenSecret
                                              );
                    handleFirebaseLogin(accessToken);
                  }).catch(function(error) {
                  })
  }

Here the handleFirebaseLogin is the function that we’ll be using to login to Firebase with the obtained access token.

Setting Up Facebook Login

Very similar to Facebook, let’s import the library and access the login function to get the access token.

const FBSDK = require('react-native-fbsdk');
const {
  LoginButton,
  AccessToken,
  LoginManager
} = FBSDK;

And the login function looks like below.

function facebookLogin() {
  if(options) {
    LoginManager.logInWithReadPermissions(['public_profile', 'email', 'user_about_me']).then(
        function(result) {
          if (result.isCancelled) {
          } else {
            AccessToken.getCurrentAccessToken().then(function(data) {
              var accessToken = Firebase.auth.FacebookAuthProvider.credential(data.accessToken);
              handleFirebaseLogin(accessToken);
            }.bind(this));
          }
        }.bind(this),
        function(error) {
        }
      );
  }
}

Setting Up Google Sign in

Like the previous platforms, Google sign in also follows the same steps.

import { GoogleSignin } from 'react-native-google-signin';
GoogleSignin.getAccessToken()
.then((token) => {
  var accessToken = Firebase.auth.GoogleAuthProvider.credential(token);
  handleFirebaseLogin(accessToken);
})
.catch((err) => {
})
.done();

Handling Firebase Login

Once you get the access token of the user, you can use the below function to authenticate him with Firebase. But you should also map the social credentials with the Firebase in the console.

function handleFirebaseLogin(accessToken, options) {
  Firebase.auth()
          .signInWithCredential(accessToken)
          .then(function(data) {
                        var user = Firebase.auth().currentUser;
          })
          .catch(function(error) {
                        var errorCode = error.code;
            var errorMessage = error.message;
            var email = error.email;
            var credential = error.credential;
            if (errorCode === 'auth/account-exists-with-different-credential') {
              // Email already associated with another account.
            }
          })
}

Once everything is setup, things will be smooth.

Also look at our previous articles if you’re getting started with Firestore,

Share article on


This is a companion discussion topic for the original entry at https://www.skcript.com/svr/firebase-social-login-with-react-native/

(Gemma Angelina) #2

The react-native-signin documentation mentions adding TwitterKit, TwitterCore and 2 other bundle files into your root folder in Xcode. Is that not necessary with the strategy proposed here?


(Varun Raj) #3

Actually the one I mentioned in the article is one type of implementation where the TwitterKit and TwitterCore comes along with the library. Thus you dont have to manually do it. Also there are a lot of new way of implementing this now.


(Gemma Angelina) #4

Any suggestions on better new ways to implement this now? I’ve been stuck on what approach to take for a little while. I’m trying to use Expo and I don’t believe they support NativeModules.


(Eduardo Gomez) #5

Can somebody help me please

import React, { Component } from 'react';
import {
    Button,
    Platform,
    StyleSheet,
    Text,
    View
} from 'react-native';

import { GoogleSignin } from 'react-native-google-signin'
import firebase from 'react-native-firebase'

let androidID = '636568644185-25p3rg795pj4ti99ctuihpkg37ro3roc.apps.googleusercontent.com';
let iosId = '636568644185-abn37uqk3vdg5rr5a0ebop0sm5g924me.apps.googleusercontent.com';

export default class App extends Component {


    componentDidMount() {
        GoogleSignin.configure({
            iosClientId: iosId

        })
    }


    onLoginGoogle = () => {

    GoogleSignin
        .signIn()
        .then((data) => {

          const credentials = firebase.auth.GoogleAuthProvider.credential(data.IdToken, data.acess)

          return firebase.auth().signInWithCredential(credentials)

        }).then((currentUser) => {

            console.log('Google loogin with user:' + JSON.stringify(currentUser.toJSON()))

        }).catch((error) => {

          console.log('Logging fail with error: ' + error)

        })

  };

  render() {
    return (
      <View style={styles.container}>
        <Button style={styles.buttonContainer}
                onPress={this.onLoginGoogle}
                title="Press Me">
        </Button>
      </View>
    );
  }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: '#F5FCFF',
    },
    buttonContainer: {
        padding: 10,
        width: 150,
        margin: 20,
        borderRadius: 4,
        backgroundColor: '#cc5441',
    }
});

I am using the react-native-google-signin package and when I sign in is crashes