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:
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