Codementor Events

React-Native: Google and Facebook Authentication

Published Oct 12, 2017
React-Native: Google and Facebook Authentication

Authentication is an integral part of any application — especially when we want to add some permissions or restrict access to certain views.

To get started, ensure that you have the following installed:

  • NodeJS
  • React-Native CLI
  • Watchman
  • Android Studio
  • XCode

If you don't have any of the above installed, you can install them on MacOS as follows:

  • NodeJS: $ brew install node
  • React-Native CLI: $ npm i -g react-native-cli
  • Watchman: $ brew install watchman
  • Android Studio: can be downloaded here
  • Xcode: can be downloaded from the App Store

NB: You must have Homebrew installed to use the brew command. It is assumed that the reader is using Mac OSX

Step 1 (Initalizing our Authentication App and installing FBSDK and google-signin)

Now that we have installed everything we need, let's get started!

Fire up your Terminal and run the following commands:

  • $ react-native init Authentication
  • $ cd Authentication
  • $ react-native install react-native-fbsdk@0.6.0
  • $ react-native install react-native-google-signin
  • $ react-native run-ios

You should have a screen similar to the one below after executing the above commands
Screen Shot 2017-10-08 at 2.42.17 PM.png

Step 2 (Configuring FBSDK in our App)

  • Facebook SDK
    Visit https://developers.facebook.com and create a new app

    • iOS configuration
      • $ open. (This will open your current directory in Finder)
      • Open Authentication.xcodeproj
      • Follow Step 2- 11 here
    • Android Configuration
      • Open our Authentication app's Android folder in Android Studio
      • Follow the steps here
      • After following the steps above, open our app level build.gradle and update the following:
        • compileSdkVersion: 25
        • targetSdkVersion: 23
        • dependencies { compile "com.android.support:appcompat-v7:25.0.0" // change from 23.0.1 }
    • Update your Android manifest as described here.
    • Run $ react-native run-andriod

    After the above steps have been completed, let's write our LogIn component and test out our configuration:

  • Create a folder components in our app directory and add a new file LogIn.js

  • Copy the code below into LogIn.js

import React, {Component} from 'react';
import {LoginManager} from 'react-native-fbsdk';
import {TouchableOpacity, Text, View} from 'react-native';

export default class LogIn extends Component {
  fbAuth() {
    LoginManager.logInWithReadPermissions(['public_profile']).then(
      function (result) {
        if (result.isCancelled) {
          console.log('Login was cancelled');
        } else {
          console.log('Login was successful with permissions: '
            + result.grantedPermissions.toString());
        }
      },
      function (error) {
        console.log('Login failed with error: ' + error);
      }
    );
  }
  render() {
    return (
      <View>
        <TouchableOpacity onPress={this.fbAuth.bind(this)}>
          <Text>Login with Facebook</Text>
        </TouchableOpacity>
      </View>
    );
  }
}
  • Import our new component into App.js in our app's root directory. Its contents should look similar to the code below:
import React, {Component} from 'react';
import {
  StyleSheet,
  View
} from 'react-native';

import LogIn from './components/LogIn';

export default class App extends Component<{}> {
  render() {
    return (
      <View style={styles.container}>
        <LogIn />
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
});

Now, let's stop the current instance of our app and run $ react-native run-ios on Terminal again. Our App screen should look similar to the screen below
Screen Shot 2017-10-08 at 6.26.49 PM.png

Let's test that our login works by clicking Login with Facebook. We should get a screen similar to that below or get a screen requesting us to enter our Facebook credentials
Screen Shot 2017-10-08 at 6.26.15 PM.png

Step 3 (Configure Google Authentication)

  • iOS configuration
    • Let's open our application node_modules folder and find react-native-google-signin and open its ios folder. It should look like the image below:
      Screen Shot 2017-10-08 at 6.52.18 PM.png
    • Drag RNGoogleSignin.xcodeproj into our Xcode project Libraries Group as shown below
      Screen Shot 2017-10-08 at 6.39.14 PM.png
    • Open the GoogleSdk folder and drag all files that end with .framework into the Frameworks group of our application and make sure "Copy items if needed" is ticked.
    • Follow Steps 2-3 here
  • Android Configuration
    • Follow the steps here.

After completing the steps above, add the following methods to our LogIn component:

  componentDidMount() {
    this.setupGoogleSignin();
  }

  googleAuth() {
    GoogleSignin.signIn()
      .then((user) => {
        console.log(user);
      })
      .catch((err) => {
        console.log('WRONG SIGNIN', err);
      })
      .done();
  }

  async setupGoogleSignin() {
    try {
      await GoogleSignin.hasPlayServices({ autoResolve: true });
      await GoogleSignin.configure({
        iosClientId: settings.iOSClientId,
        webClientId: settings.webClientId,
        offlineAccess: false
      });

      const user = await GoogleSignin.currentUserAsync();
      console.log(user);
    }
    catch (err) {
      console.log("Google signin error", err.code, err.message);
    }
  }

Also, in our LogIn component's render methodm, add the Google Login button like it's shown below:

<TouchableOpacity onPress={this.googleAuth.bind(this)}>
  <Text>Login with Google</Text>
</TouchableOpacity>

Now, let's stop our current application process and run $ react-native run-ios again. Our screen should look like the one below:
Screen Shot 2017-10-08 at 8.15.42 PM.png

Let's test that our login works by clicking Login with Google. We should get a screen similar to that below or get a screen requesting us to enter our Google credentials
Screen Shot 2017-10-08 at 8.17.16 PM.png

Summary

Now that we have authentication set up in our application, we can customize persisting user information any way we want. Source code for this article can be found here.

Discover and read more posts from Atanda Abdul-Semiu
get started
post comments6Replies
Krissanawat Kaewsanmuang
4 years ago

Thanks for this short and simple tutorial on implementing google and Facebook authentication using React Native Google SignInand Fbsdk. The screenshots help a lot while going through the article and implementing it simultaneously. Easy to understand and accurate as well. Highly recommended.

SamuelEVicente
6 years ago

Hello Atanda, by any chance do you mentor? I didn’t see where I could message you or schedule a session. Thanks for this article.

Виктор Мартынюк
7 years ago

iOS, if you get error like this “ld: framework not found GoogleSymbolUtilities”

Go to “Build Settings” and add to “Framework Search Paths” path to GoogleSdk: default $(PROJECT_DIR)/…/node_modules/react-native-google-signin/ios/GoogleSdk

Show more replies