Using Phone Number Authentication

Tutorial 4 of 5

1. Introduction

In this tutorial, we will be focusing on implementing phone number authentication using Firebase Authentication. We will learn how to send a One-Time Password (OTP) to a user's phone number and verify the received OTP using Firebase SDK methods.

By the end of this tutorial, you'll be able to incorporate phone number authentication into your own web applications.

Prerequisites

  • Basic knowledge of JavaScript.
  • Familiarity with Firebase and its services.
  • An active Firebase project.

2. Step-by-Step Guide

Firebase provides several methods for authenticating users, one of which is phone number authentication. This method involves sending an OTP to the user's phone number. The user then inputs this OTP, and Firebase verifies it.

Steps:

  1. Set up Firebase in your project: If you haven't already, add Firebase to your JavaScript project following the guidelines in the Firebase documentation.
  2. Enable Phone Number sign-in for your Firebase project: In the Firebase console, go to the Authentication section and enable the Phone Number sign-in method.
  3. Set up reCAPTCHA: Firebase uses reCAPTCHA to prevent misuse. You'll need to set up a reCAPTCHA verifier and attach it to an HTML element.
  4. Send the OTP: Use the signInWithPhoneNumber method to send the OTP to the user's phone number.
  5. Verify the OTP: Finally, use the confirm method with the code the user inputs to verify the OTP.

3. Code Examples

Here are some practical examples of the steps mentioned above:

Example 1: Setting up Firebase

Before using Firebase, you need to set up your Firebase project and add Firebase to your app. Follow the Firebase documentation for these steps.

<script src="https://www.gstatic.com/firebasejs/8.2.1/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.2.1/firebase-auth.js"></script>

<script>
  // Your Firebase configuration
  var firebaseConfig = {
    apiKey: "your-api-key",
    authDomain: "your-auth-domain",
    projectId: "your-project-id",
    storageBucket: "your-storage-bucket",
    messagingSenderId: "your-messaging-sender-id",
    appId: "your-app-id"
  };

  // Initialize Firebase
  firebase.initializeApp(firebaseConfig);
</script>

Example 2: Enabling Phone Number Sign-In

In the Firebase console, go to the Authentication section, and under the Sign-In Method tab, enable the Phone Number sign-in method.

Example 3: Setting Up reCAPTCHA and Sending OTP

var recaptchaVerifier = new firebase.auth.RecaptchaVerifier('sign-in-button', {
  'size': 'invisible',
  'callback': function(response) {
    // reCAPTCHA solved - will proceed with signInWithPhoneNumber.
    onSignInSubmit();
  }
});

var phoneNumber = getPhoneNumberFromUserInput();
var appVerifier = window.recaptchaVerifier;
firebase.auth().signInWithPhoneNumber(phoneNumber, appVerifier)
    .then(function (confirmationResult) {
      window.confirmationResult = confirmationResult;
    }).catch(function (error) {
      console.error("SMS not sent", error);
    });

function getPhoneNumberFromUserInput() {
  // Here you would retrieve the phone number from the user.
  // This is just a placeholder.
  return '+12345678900';
}

Example 4: Verifying the OTP

var code = getCodeFromUserInput();
confirmationResult.confirm(code).then(function (result) {
  var user = result.user;
}).catch(function (error) {
  console.error("OTP not verified", error);
});

function getCodeFromUserInput() {
  // Here you would retrieve the OTP from the user.
  // This is just a placeholder.
  return '123456';
}

4. Summary

In this tutorial, we walked through the process of setting up phone number authentication using Firebase. We learned how to enable phone number sign-in in the Firebase console, how to set up reCAPTCHA, and how to send and verify OTPs.

Next, consider exploring other Firebase authentication methods, such as email/password authentication or Google Sign-In.

5. Practice Exercises

  1. Build a login page that uses phone number authentication.
  2. Handle potential errors that may occur during the phone number authentication process.
  3. Extend your login page to give users the option to authenticate with either their phone number or their email address.

Remember, the best way to learn is by doing. Happy coding!