Firebase Phone Authentication in React Native

Introduction

Phone authentication allows users to sign in to Firebase using their phone as the authenticator. An SMS message is sent to the user via their phone number containing a unique code. Once the code has been authorized, the user is able to sign in to Firebase.
Enabling the “Phone” sign-in provider on the Firebase Console is a crucial step for implementing phone authentication in your React Native app. Here’s a step-by-step guide on how to ensure the “Phone” sign-in provider is enabled:

  • Open the Firebase Console.
  • Select your Firebase project or create a new one.
  • On the left sidebar, click on “Authentication” to go to the Authentication section.
  • In the Authentication section, select the “Sign-in method” tab.
  • Scroll down to find the “Phone” sign-in provider. If it’s not enabled, you’ll see an “Enable” button.
  • Click on the “Phone” sign-in provider.
  • Toggle the switch to enable the phone sign-in provider.

Definition and Importance

  1. User Verification: Phone authentication involves confirming that the person trying to access an    application is the rightful owner of the provided mobile phone number.
  2. One-Time Code: A unique, one-time verification code is sent to the user’s phone via SMS or a mobile app.
  3. User Input: The user inputs the received code into the application to complete the authentication process. 

Advantages of Phone Authentication

Ease of Integration: Firebase provides a straightforward and well-documented SDK for various platforms, including React Native. Integrating phone authentication into your app is simplified with Firebase.

Security: Firebase’s phone authentication is built with security in mind. It uses secure, encrypted communication between the app and Firebase servers, reducing the risk of man-in-the-middle attacks.

Multi-Platform Support: Firebase supports authentication across various platforms, including Android, iOS, and web applications. This allows for a consistent user experience across different devices.

Phone Number as User Identifier: Firebase allows developers to use the phone number as a unique identifier for users. This simplifies user management and helps in creating a seamless authentication experience.

Integrate Firebase Authentication

yarn add @react-native-firebase/app(Setup firebase in your app. Follow this https://rnfirebase.io/)
yarn add @react-native-firebase/auth

 

Code

import React, { useState, useEffect } from ‘react’;

import auth from ‘@react-native-firebase/auth’;

const PhoneAuthentication = ()=>{

const [confirmation, setConfirmation] = useState(null); 

const [phoneNumber, setPhoneNumber] = useState(‘ ’); 

const [otp, setOtp] = useState(‘ ‘);

//when you successfully use signInWithPhoneNumber to complete the phone authentication process, it may lead to changes in the user’s authentication state, triggering the onAuthStateChanged listener if the user is successfully signed in.

 useEffect(() => {

    const unsubscribe = auth().onAuthStateChanged(async user => {

      if (user) {

       // Some Android devices can automatically process the verification code (OTP) message, and the user would NOT need to enter the code.

      // Actually, if you tries to enter it (do this await confirmation.confirm(otp)), you will get an error message because the code was already used in the background.

      // In this function, make sure you hide the component(s) for entering the code and/or navigate away from this screen.

     // It is also recommended to display a message to the user informing him/her that he/she has successfully logged in.

 

        const token = await user?.getIdToken();

        if (token) {

         // You can perform additional actions here or navigate to the next screen

        }

      }

    });

    return () => {

      unsubscribe();

    };

  }, [ ]);

//this code is for sending otp

const signInWithPhoneNumber = async () => {

if(phoneNumber.length ===0)

return;

    try {

      const confirmation = await auth().signInWithPhoneNumber(phoneNumber);

      if (confirmation) {

        setConfirmation(confirmation);

        }

    } catch (error) {

      console.error(error?.message);

      if (error.code == ‘auth/too-many-requests’) {

        Alert.alert(

          ‘We have blocked all requests from this device due to unusual activity. Try again later.’,

        );

      } else {

        Alert.alert(

          ‘Something went wrong!. Please try again later.’,

        );

      }

    }

  };

//this code is for validating otp

const confirmCodeHandler = async () => {

    try {

      await confirmation.confirm(otp);

      const idToken = await auth().currentUser.getIdToken(); //this is for getting auth token.

      Alert.alert( ‘Phone number confirmed!’);

      //  You can perform additional actions here or navigate to the next screen

    } catch (error) {

if (error.code == ‘auth/session-expired’) {

        Alert.alert(

          ‘The sms code has expired. Please resend the verification code to try again’,

        );

        return;

      } else if (error.code == ‘auth/invalid-verification-code’) {

        Alert.alert(

          ‘The verification code is invalid. Please check and enter the correct verification code again.’,

        );

      }

      console.log(‘Error confirming verification code:’, error);

       }

  };

 

return (

    // your code design

  );

};

export const PhoneAuthentication;