Phone Number Authentication Using Firebase

What is Firebase phone authentication?

 
Firebase is a mobile and web application development platform.  It provides various features and functionalities.
 
Phone authentication is one of its features, which provides authentication using mobile numbers along with the country code.
 
Firebase Initialization or configuration Settings
  1. import * as firebase from 'firebase'  
  2. import 'firebase/firestore';  
  3.   
  4. const firebaseConfig = {  
  5.   apiKey: "XXXX-XXXX-XXXX",  
  6.   authDomain: "XXXX-app-web.firebaseapp.com",  
  7.   databaseURL: "https://XXXX-app-web.firebaseio.com",  
  8.   projectId: "XXXX-app-web",  
  9.   storageBucket: "XXXX-app-web.appspot.com",  
  10.   messagingSenderId: "XXXXXXXXXX",  
  11.   appId: "1:XXXX:web:XXXXXX",  
  12.   measurementId: "G-XXXXXXX"  
  13. };  
  14.   
  15. export default !firebase.apps.length ? firebase.initializeApp(firebaseConfig).firestore() : firebase.app().firestore()
Note
Please refer to my earlier blog to get Firebase configuration details. You need to first add your application on the Firebase console and then create one web app in which you can get all details of configuration of the Firebase app.
 
After successful configuration of the Firebase App, you need to follow a few steps to integrate functionality of Phone Number Authentication using Firebase.
  • Enable Phone Authentication in Firebase console
  • Cofigure the reCAPTCHA verifier
  • Send a verification code to a phone number
  • Verify the six digit code which is sent on the phone number & sign in
  • Sign out from Firebase Console
STEP 1 - Enable Phone Authentication in Firebase console
 
Once the web app is created and credentials have been set, we need to enable phone authentication mode from the Firebase console. From the left sidebar there will be an option for Authentication. Once you click on the Authentication menu there will be an option for Sign-In Method.
 
Phone Number Authentication Using Firebase

Once you click on Sign-In Method, a new list with the multiple sign in providers will appear. From that list you need to choose the Phone option to enable it. So you need to click on the pencil icon which will appear when you hover on Phone from the list. You need to eneble the phone authentication from the screen just like the below images.
 
Phone Number Authentication Using Firebase
 
Phone Number Authentication Using Firebase
 
There will be an option to test authentication as well, so you can click on it. There, you need to provide the number. It will automatically send the verification code to the given number. In  this way you can test and verify the authentication using your phone number.
 
Phone Number Authentication Using Firebase
 
STEP 2 - Cofigure the reCAPTCHA verifier

Once you enable the phone authentication mode to on, you need to configure reCAPTCHA verifier for Firebase which will prevent abuse. 

We do not have to set up reCAPTCHA manually, SDK itself provides an options to configure reCAPTCHA functionality.

Firebase provides two properties for captcha size
  • Normal
    A visible captcha code to the user; and the captcha process is manual.

  • Invisible
    An  invisible captcha code, automated captcha process is auto rendered in DOM.
  1. captchaInit = () => {  
  2.    if (this.applicationVerifier && this.recaptchaWrapperRef) {  
  3.      this.applicationVerifier.clear()  
  4.      this.recaptchaWrapperRef.innerHTML = `<div id="recaptcha-container"></div>`  
  5.    }  
  6.   
  7.    this.applicationVerifier = new firebase.auth.RecaptchaVerifier(  
  8.      "recaptcha-container",  
  9.      {  
  10.        size: "invisible"  
  11.      }  
  12.    );  
  13.  } 

Above captchaInit method is a separated function which we can reinitilize whenever it's called from code.
  1. <div ref={ref => this.recaptchaWrapperRef = ref}>    
  2.        <div id="recaptcha-container"></div>    
  3. </div> 
STEP 3 - Send a verification code to Phone number
 
There is a predefined auth method of Firebase SDK which you can use to send a verification code to the provided number.

Note
Mobile number must be with country dial code, for example: If you are from India then your number should be "+91 **********".
  1. // phoneNumber : which you need to get from the input of Phone number    
  2. // appVerifier : window.recaptchaVerifier object automatically set once initialize the method    
  3.     
  4. firebase.auth().signInWithPhoneNumber(phoneNumber, appVerifier)    
  5.     .then(function (confirmationResult) {    
  6.       // SMS sent. On you mobile SMS will automatically sent via Firebase    
  7.       // save with confirmationResult.confirm(code).    
  8.       window.confirmationResult = confirmationResult;    
  9.     }).catch(function (error) {    
  10.       // Error; SMS will not sent    
  11.     });   
STEP 4 - Verify the six digit code which is sent on Phone number & Sign-In
 
After calling the above mentioned method using Phone number and reCAPTCHA verifier, you will get notification of a SIX DIGIT CODE on your Phone  which is sent via Firebase.

You can use Firebase SDK's predefined fuction, as below.
  1. // code = Need to get from user input  
  2.   
  3. confirmationResult.confirm(code).then(function (result) {  
  4.   // User signed in successfully.  
  5.    var user = result.user;  
  6. }).catch(function (error) {  
  7.   // Wrong code added.  
  8. }); 
In case the verification code is invalid then the method will return a successful result with information of user details.

STEP 5 - SignOut from Firebase Console
 
In case you have a logout button on your screen or module you can sign out a user using the below method.
  1. firebase.auth().signOut().then(function() {  
  2.   // SignOut successful.  
  3. }).catch(function(error) {  
  4.   // Something wrong happened.  
  5. }) 

Summary

 
In the article, I've explained step by step implementation of Phone authentication using Firebase service. There is a limit quota for Firebase service calls, which you can refer to using Firebase Usage and limits.
 
Phone Number Authentication Using Firebase
For  a working example in React please go through Git Repository - (Firebase -> Phone Number Verification)


Similar Articles