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
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.
Contact Us