Firebase Phone Number Authentication
Firebase provides phone number authentication service for apple, android and web to help the to sign-up and log-in user using their phone number by sending them verification code (OTP). Follow the step the enable Phone Number Authentication for web.
1. Enable Phone Number sign-in for your Firebase project
- Open your project console and navigate to
Build
>Authentication
dashboard in that open Sign-in method tab. - Click on "Add new provider" and choose Phone that is in Native Provider column.
- Now enable Phone provider and hit Save button.Now you can use Phone Number to sign-in and authenticate user in firebase web.
2. Set up the reCAPTCHA verifier
You need to configure Firebase's reCAPTCHA verifier before allowing users to sign in with their phone numbers. Firebase uses reCAPTCHA to stop misuse, such as by making sure the request for a phone number verification comes from one of the permitted domains for your app.
So for that first create an
div
and assign it an id="recaptchaContainer" attribute.<div id="recaptchaContainer"></div>
import { auth } from "<YOUR_FIREBASE_CONFIG_FILE_PATH>"; //see setup and initialize authentication if you have any doubt
import { RecaptchaVerifier } from "firebase/auth";
function recaptchaGenerator() {
auth.useDeviceLanguage(); //set device language
return new RecaptchaVerifier(
"recaptchaContainer",
{
size: "invisible",
},
auth,
);
}
3. Send a verification code to the user's phone
Use this code to send OTP on user's phone number in firebase phone number authentication.
import { auth } from "<YOUR_FIREBASE_CONFIG_FILE_PATH>"; //see setup and initialize authentication if you have any doubt
import { signInWithPhoneNumber } from "firebase/auth";
const sendVerificationCode = async () => {
try {
const appVerifier = recaptchaGenerator(); // This is create for reCAPTCHA verifier [In STEP(2)]
window.confirmationResult = await signInWithPhoneNumber(
auth,
"+10000000000", // Enter number along with country code
appVerifier,
);
} catch (error) {
console.log(error);
}
};
sendVerificationCode
function when you submit the number.4. Sign in the user by verifying OTP code
This code perform the task to verify the entered OTP and help to sign in user phone authentication in firebase.
const verifyOTP = () => {
window.confirmationResult
.confirm("OTP_CODE")
.then((result) => {
const userData = result;
// ... write code to perform intened task
// ...
})
.catch((error) => console.log(error));
};
verifyOTP
function when you submit the OTP to verify.Related Post
Setup and Initialize
Phone number
Email/Password
Email link (Passwordless)
Explore
Copyright © 2024, All rights reserved by Firebase Master