Whatsapp Like Phone Number Authentication with Firebase
Firebase Authentication with phone number can sign in a user by sending an SMS message to the user’s phone. The user signs in using a one-time code contained in the SMS message. This is liken to Whatsapp and other app who have this features already. Conventionally authentication has been done with emails and social login platforms only a few apps used the Phone Number Auth feature. Now that it live on firebase , Let see how to integrate it into our Apps.
— — Getting Started
1. Connect Firebase to your Android project
- On your Android Studio tools
- On the Firebase Assistant Menu select
Authentication
- Click on
Connect to Firebase
to connect your app with any of your Firebase Projects
- From the dialog select the Firebase project you wish to connect your app with and Click
Connect to Firebase
- Set your app’s SHA-1 hash in the Firebase console, do so. See Authenticating Your Client for information about finding your app’s SHA-1 hash.
2. Configure Firebase Authentication
- Add the dependency for Firebase Authentication to your app-level
build.gradle
file:
compile `com.google.firebase:firebase-auth:11.8.0`
3. Enable Phone Number sign-in for your Firebase project
To be able to authenticate user by SMS , you must first enable Phone Number sign-in method in your Firebase console and click save
4. Send a verification code to the user’s phone
To initialize the Sign-in process , present the user a screen to input his/her phone number . Also note: Alway let the user know they might receive an SMS message for verification and standard rates apply. For this post we will be use firebase UI
Then, pass their phone number to the PhoneAuthProvider.verifyPhoneNumber
method to request that Firebase verify the user's phone number. For example:
PhoneAuthProvider.getInstance().verifyPhoneNumber(
phoneNumber, // Phone number to verify
60, // Timeout duration
TimeUnit.SECONDS, // Unit of timeout
this, // Activity (for callback binding)
mCallbacks); // OnVerificationStateChangedCallbacks
When you call PhoneAuthProvider.verifyPhoneNumber
, you must also provide an instance of OnVerificationStateChangedCallbacks
, which contains implementations of the callback functions that handle the results of the request. For example:
onVerificationCompleted:
This callback will be invoked in two situations:
1 — Instant verification. verified without needing to send or enter a verification code.
2 — Auto-retrieval. On some devices Google Play services can automatically detect the incoming verification SMS and perform verification without user action.
mCallbacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {@Overridepublic void onVerificationCompleted(PhoneAuthCredential credential) {Log.d(TAG, “onVerificationCompleted:” + credential);signInWithPhoneAuthCredential(credential);}
OnVerificationFailed
: This callback is invoked when an invalid request for verification is made,
@Overridepublic void onVerificationFailed(FirebaseException e) {if (e instanceof FirebaseAuthInvalidCredentialsException) {// Invalid request} else if (e instanceof FirebaseTooManyRequestsException) {// The SMS quota for the project has been exceeded }}
onCodeSent
This callback is called when the SMS verification code has been sent to the provided phone number.
@Overridepublic void onCodeSent(String verificationId,PhoneAuthProvider.ForceResendingToken token) {Log.d(TAG, “onCodeSent:” + verificationId);// Save verification ID and resending token so we can use them latermVerificationId = verificationId;mResendToken = token;// …}
Create a PhoneAuthCredential object
create a PhoneAuthCredential
object, using the verification code and the verification ID that was passed to the onCodeSent
PhoneAuthCredential credential = PhoneAuthProvider.getCredential(verificationId, code);
5. Sign In User
complete the sign-in flow by passing the PhoneAuthCredential
object to FirebaseAuth.signInWithCredential
:
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
// Sign in success, update UI with the signed-in user's information
Log.d(TAG, "signInWithCredential:success");
FirebaseUser user = task.getResult().getUser();
startActivity(new Intent(getApplicationContext(), Main2Activity.class));
} else {
// Sign in failed, display a message and update the UI
Log.w(TAG, "signInWithCredential:failure", task.getException());
if (task.getException() instanceof FirebaseAuthInvalidCredentialsException) {
// The verification code entered was invalid
smsCodeVerificationField.setError("Invalid code.");
}
}
}
});
You are done.
Oops! this has not totally finished , we will need to handle lifecycle problems in our future post.
Full source code here
If it helps, Do well to give a clap.