Firebase Phone Authentication

Phone Authentication in Firebase is a secure method of verifying user identities using their phone numbers. It simplifies the sign-in process by sending verification codes via SMS and ensuring that only users with access to the phone number can sign in.

In this article, We will learn to set up and implement Phone Authentication in Firebase for our web application.

What is Phone Authentication?

  • Phone Authentication in Firebase is a method of verifying users identities using their phone numbers. It allows users to sign in to our app using a code sent to their phone via SMS.
  • Firebase Authentication handles the process of sending verification codes to users phones and verifying those codes, providing a secure and user-friendly way to authenticate users.
  • Phone Authentication in Firebase is a robust feature that offers several benefits:
    • User-Friendly: It provides a simple and intuitive sign-in process for users, requiring only their phone numbers.
    • Secure: Firebase handles the verification process, ensuring that only users with access to the phone number can sign in.
    • Two-Factor Authentication (2FA): It offers an additional layer of security by combining something the user knows their password.

Setting Up Firebase Project

Before we dive into the implementation, you need to set up a Firebase project and integrate it into your app:

  • Create a Firebase Project: Go to the Firebase Console, create a new project, and follow the setup instructions.
  • Add Firebase to Your App: Firebase provides detailed guides for adding Firebase to various platforms. Follow the instructions specific to your platform (Web, iOS or Android) to include Firebase in your project.
  • Enable Phone Authentication:
    • Navigate to the Authentication section in the Firebase Console.
    • Select the Sign-in method tab.
    • Enable Phone as a sign-in provider.

Implementing Phone Authentication

1. Adding Firebase SDK to Your Project

For a web application, include the Firebase SDK in your HTML file:

<!-- Firebase App (the core Firebase SDK) -->
<script src="https://www.gstatic.com/firebasejs/9.6.4/firebase-app.js"></script>

<!-- Firebase Auth (for authentication) -->
<script src="https://www.gstatic.com/firebasejs/9.6.4/firebase-auth.js"></script>

2. Initialize Firebase

Initialize Firebase in your JavaScript file using the configuration details from your Firebase project settings:

const firebaseConfig = {
apiKey: "AIzaSyDmaZAcK7xwQTAsQJxaGnG56oB8RIJDMnc",
authDomain: "samplep-d6b68.firebaseapp.com",
projectId: "samplep-d6b68",
storageBucket: "samplep-d6b68.appspot.com",
messagingSenderId: "398502093281",
appId: "1:398502093281:web:5d685b0733d4d6d66472a0",
measurementId: "G-9E6K9YD8D1"
};

// Initialize Firebase
firebase.initializeApp(firebaseConfig);

3. Setting Up Recaptcha Verifier

Firebase requires a reCAPTCHA verifier to ensure that phone authentication requests are made by real users:

const recaptchaVerifier = new firebase.auth.RecaptchaVerifier('recaptcha-container', {
'size': 'invisible',
'callback': function(response) {
// reCAPTCHA solved - allow signInWithPhoneNumber
}
});

Explanation: This code initializes an invisible reCAPTCHA verifier (RecaptchaVerifier) for phone authentication in Firebase. When the reCAPTCHA challenge is solved, it allows the signInWithPhoneNumber function to proceed

4. Sending Verification Code

Create a function to handle sending the verification code to the user’s phone number:

function sendVerificationCode(phoneNumber) {
const appVerifier = recaptchaVerifier;
firebase.auth().signInWithPhoneNumber(phoneNumber, appVerifier)
.then((confirmationResult) => {
// SMS sent. Prompt user to type the code from the message
window.confirmationResult = confirmationResult;
})
.catch((error) => {
// Handle errors here
console.error('Error during sign-in:', error.message);
});
}

Explanation: This function sends a verification code to the provided phone number using Firebase authentication. It uses the signInWithPhoneNumber method with the reCAPTCHA verifier (appVerifier) to initiate the verification process. If successful, it stores the confirmationResult for further verification. If there’s an error, it logs the error message.

5. Verifying the Code

Create a function to verify the code entered by the user:

function verifyCode(verificationCode) {
confirmationResult.confirm(verificationCode)
.then((result) => {
// User signed in successfully
const user = result.user;
console.log('User:', user);
})
.catch((error) => {
// Handle errors here
console.error('Error during verification:', error.message);
});
}

Explanation: This function verifies the code entered by the user for phone authentication. It uses the confirm method on confirmationResult (previously obtained from signInWithPhoneNumber) to complete the authentication process. If successful, it logs the user information. If there’s an error, it logs the error message.

6. Handling User Authentication State

Monitor the user’s authentication state to check if they are signed in:

firebase.auth().onAuthStateChanged((user) => {
if (user) {
// User is signed in
console.log('User is signed in:', user);
} else {
// No user is signed in
console.log('No user is signed in');
}
});

Explanation: This code sets up a listener for authentication state changes using Firebase Authentication. When the authentication state changes (i.e., a user signs in or signs out), the provided callback function is called. If a user is signed in, it logs the user information. If no user is signed in, it logs a message indicating that

Example: Phone Authentication in Action

Let’s put it all together in a simple web application where users can sign in using their phone numbers.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Firebase Phone Authentication</title>
</head>
<body>
<h1>Sign In with Phone Number</h1>

<div id="recaptcha-container"></div>

<input type="text" id="phone-number" placeholder="Enter phone number">
<button onclick="sendVerificationCode()">Send Verification Code</button>

<input type="text" id="verification-code" placeholder="Enter verification code">
<button onclick="verifyCode()">Verify Code</button>

<script src="https://www.gstatic.com/firebasejs/9.6.4/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/9.6.4/firebase-auth.js"></script>
<script>
const firebaseConfig = {
apiKey: "AIzaSyDmaZAcK7xwQTAsQJxaGnG56oB8RIJDMnc",
authDomain: "samplep-d6b68.firebaseapp.com",
projectId: "samplep-d6b68",
storageBucket: "samplep-d6b68.appspot.com",
messagingSenderId: "398502093281",
appId: "1:398502093281:web:5d685b0733d4d6d66472a0",
measurementId: "G-9E6K9YD8D1"
};

// Initialize Firebase
firebase.initializeApp(firebaseConfig);

const recaptchaVerifier = new firebase.auth.RecaptchaVerifier('recaptcha-container', {
'size': 'invisible',
'callback': function(response) {
// reCAPTCHA solved - allow signInWithPhoneNumber
}
});

let confirmationResult;

function sendVerificationCode() {
const phoneNumber = document.getElementById('phone-number').value;
const appVerifier = recaptchaVerifier;
firebase.auth().signInWithPhoneNumber(phoneNumber, appVerifier)
.then((confirmationResult) => {
window.confirmationResult = confirmationResult;
console.log('Verification code sent');
})
.catch((error) => {
console.error('Error during sign-in:', error.message);
});
}

function verifyCode() {
const verificationCode = document.getElementById('verification-code').value;
confirmationResult.confirm(verificationCode)
.then((result) => {
const user = result.user;
console.log('User:', user);
alert('Verification successful! User signed in.');
})
.catch((error) => {
console.error('Error during verification:', error.message);
alert('Verification failed. Please try again.');
});
}

firebase.auth().onAuthStateChanged((user) => {
if (user) {
console.log('User is signed in:', user);
} else {
console.log('No user is signed in');
}
});
</script>
</body>
</html>

Output:

Conclusion

Overall, Implementing Phone Authentication in Firebase provides a user-friendly and secure way for users to sign in to your web application. By following the steps outlined in this guide, you can enhance the authentication process and improve the overall user experience. Firebase Authentication offers additional features like Two-Factor Authentication (2FA) and user management, making it a comprehensive solution for your authentication needs



Contact Us