Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

react native
communitycreator

How to add Apple authentication to your React Native app

Gautham Vijayan

Overview

In this shot, we’ll learn to integrate Apple authentication in React Native for iOS versions of the application.

Installation

  1. Create a new React Native application from the terminal.
npx react-native init authtutorial
cd authtutorial
  1. Go to the firebase dashboard and create an android and iOS application named com.authtutorial ( or your app’s name). We’ll get two files:
  • googleservices.json for android.
  • googleServices-Info.plist for iOS.

We’ll need these two files for integrating firebase services in our React Native application.

Installation for iOS

Download the googleServices-Info.plist from the firebase dashboard and drag and drop it into Xcode.

Follow the steps below for Firebase configuration with an iOS version of your app.

  1. Go to AppDelegate.m and add the code to initialise firebase in your iOS app.

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// include the below Code
  if ([FIRApp defaultApp] == nil) {
      [FIRApp configure];
    }

2.Add <code> #import <Firebase.h> </code> at the top of the file.

iOS

  • Install the required npm packages from the terminal.
npm install --save @react-native-firebase/app @react-native-firebase/auth @invertase/react-native-apple-authentication
  • Run the command to install pods in your project in the terminal.
cd ios 
pod install
  • In App.js, add the code which enables Apple authentication for our React Native application.
import React, {useState, useEffect} from 'react';
import {SafeAreaView, Text, TouchableOpacity, View} from 'react-native';
import auth from '@react-native-firebase/auth';

import {
  appleAuth,
  AppleButton,
} from '@invertase/react-native-apple-authentication';

const App = () => {
  const [user, setUser] = useState(null);

  async function onAppleButtonPress() {
    const appleAuthRequestResponse = await appleAuth.performRequest({
      requestedOperation: appleAuth.Operation.LOGIN,
      requestedScopes: [appleAuth.Scope.EMAIL, appleAuth.Scope.FULL_NAME],
    });

    if (!appleAuthRequestResponse.identityToken) {
      throw 'Apple Sign-In failed - no identify token returned';
    }

    const {identityToken, nonce} = appleAuthRequestResponse;
    const appleCredential = auth.AppleAuthProvider.credential(
      identityToken,
      nonce,
    );

    return auth().signInWithCredential(appleCredential);
  }

  const onAuthStateChanged = async userAuth => {
    if (!userAuth) {
      return;
    }
    if (userAuth) {
      console.log(userAuth);
      setUser(userAuth);
    }

    return () => userReference();
  };
  useEffect(() => {
    const subscriber = auth().onAuthStateChanged(onAuthStateChanged);
    return () => {
      subscriber;
    };
  }, []);

  const signOut = async () => {
    auth().signOut();

    setUser(null);

    return () => userReference();
  };

  return (
    <SafeAreaView style={{alignItems: 'center', flex: 1, marginTop: 100}}>
      <View style={{margin: 10}}>
        <Text>Apple Sign In Tutorial</Text>
      </View>

      <View style={{margin: 10}}>
        {user === null && (
          <AppleButton
            buttonStyle={AppleButton.Style.BLACK}
            buttonType={AppleButton.Type.SIGN_IN}
            style={{width: 312, height: 48}}
            onPress={() =>
              onAppleButtonPress().then(() =>
                console.log('Apple sign-in complete!'),
              )
            }
          />
        )}
      </View>
      {user !== null && (
        <View style={{margin: 10}}>
          <Text style={{margin: 10}}>{user.displayName}</Text>
          <TouchableOpacity onPress={signOut} style={{alignItems: 'center'}}>
            <Text>Sign Out</Text>
          </TouchableOpacity>
        </View>
      )}
    </SafeAreaView>
  );
};

export default App;

Explanation

  • Lines 1 to 8: We import the necessary packages to be used in the application.

  • Line 11: Create a useState variable to store the user data.

  • Lines 13 to 30: We create a function to authenticate the user with Apple OAuth by getting the user email and password.

  • Lines 32 to 48: We create a function that listens to the authentication change when the user logs in with its Apple id.

  • Lines 50 to 56: We create a function to sign out the user.

  • Lines 58 to 90: We create a button for both sign-in and sign-out functions and when the user is signed in we show its email id to the user.

Conclusion

In this shot, we learned to add Apple authentication to our React Native application.

RELATED TAGS

react native
communitycreator
RELATED COURSES

View all Courses

Keep Exploring