Today we will learn about Firebase Phone Authentication. Firebase is fantastic, and it provides almost the features that you need for the backend of your application. So in this tutorial, we will learn about Firebase Phone Authentication, and I am pretty sure that you have already seen this thing in many apps. You enter your phone number, receives an OTP, and then you use that OTP to authenticate.
Table of Contents
Firebase Phone Authentication Video
- If you are more comfortable in watching video, where you will see me doing all the stuffs in real then you can skip this post and watch the video instead.
- Don’t forget to SUBSCRIBE to Simplified Coding on YouTube.Â
Benefits of using Phone Authentication
When you use phone number authentication, you have many benefits like
- Preventing Fake Users: When you use phone authentication, the user can’t be able to register for multiple accounts, as for each account a unique phone number is needed.
- Increase User Value: When you have all the users verified by a phone number the value of your user base increases.
- Increased Security and User Experience:Nowadays more people using apps and remembering passwords are a headache for many users, so they end up using weak passwords. Using phone authentication increases security and user experience, as the user does not need to create and remember passwords, they will enter their number and then they can receive a temporary authentication code by SMS.
Why Firebase Phone Authentication?
For implementing phone authentication you need to pay for SMS service, but with firebase, you can do it for FREE, isn’t it awesome? The free plan of firebase has Ten Thousand Verification per month. Thats enough for the starter apps I guess, but yes if you exceed this limit, you need to pay.
So, guys enough for the discussion now let’s start our project and let’s see how we can integrate phone authentication in our application.
Firebase Phone Authentication Tutorial
Now let’s learn how to implement Firebase Phone Authentication in our project.
Creating a new Android Studio Project
- Again we will do it in a new project, so create a new Android Studio project. In my case I have created a project named FirebasePhoneAuthentication.
- Once the project is completely loaded, we will add firebase authentication into it.
Adding Firebase Authentication
- Click on tools -> firebase. It will open an assistant from where you can add all the firebase services into your project.
- So from here you can create a new firebase project or you can also select an existing project.
- Connect your android project to firebase project and add the dependencies using this assistant.
If you are confused about this step please follow this Firebase Cloud Messaging Tutorial where I explained all the steps about adding firebase to android project.Â
Enable Firebase Phone Authentication
- To do this go to Firebase Console and open the project that you are using.
- Then go to Sign In Method and enable Phone Authentication.
Designing Screens
Before moving into designing I would like to tell you that, for Sign In we will have two activities, in the first activity the user will enter his phone number and in the next we will verify the code sent by SMS.
Enter Phone Number Screen
- I have created this design for this Screen.
- For designing the above screen come inside activity_main.xml and write the following xml code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 |
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <RelativeLayout android:id="@+id/relativeLayout" android:layout_width="match_parent" android:layout_height="200dp" android:background="@color/colorPrimary" android:orientation="horizontal"> <ImageView android:layout_width="120dp" android:layout_height="120dp" android:layout_centerHorizontal="true" android:layout_centerVertical="true" android:background="@drawable/ic_logo" /> </RelativeLayout> <ImageView android:id="@+id/imageView" android:layout_width="match_parent" android:layout_height="120dp" android:layout_below="@id/relativeLayout" android:layout_marginTop="-50dp" android:background="@drawable/waves" /> <RelativeLayout android:id="@+id/container" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_below="@id/imageView" android:orientation="vertical" android:padding="20dp"> <TextView android:id="@+id/textView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_marginTop="25dp" android:text="May I ask your phone number?" android:textAppearance="@style/Base.TextAppearance.AppCompat.Headline" android:textColor="@color/colorPrimary" /> <EditText android:id="@+id/editTextMobile" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@id/textView" android:layout_marginTop="20dp" android:digits="0123456789" android:drawableLeft="@drawable/ic_phone" android:drawablePadding="10dp" android:hint="enter your mobile number" android:inputType="phone" android:maxLength="10" /> <Button android:id="@+id/buttonContinue" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/editTextMobile" android:layout_centerHorizontal="true" android:layout_marginTop="15dp" android:background="@color/colorPrimaryDark" android:text="Continue" android:textAllCaps="false" android:textColor="#cdd8f1" /> </RelativeLayout> </RelativeLayout> |
- The above xml file will give you some errors as I have used some drawable resources, but don’t worry you can get the resources in my source code and the link of the source code is at the bottom, so keep reading.Â
Verify Phone Number Screen
Now we will create the next activity where we will very the phone number. In this screen as well we need an EditText where user will input the code. But we will detect the SMS automatically so user do not need to enter manually.
- First create a new Activity in the project, and I have created an activity named VerifyPhoneActivity.
- For the above design for your VerifyPhoneActivity, open the activity_verify_phone.xml and write the following xml code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 |
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".VerifyPhoneActivity"> <RelativeLayout android:id="@+id/relativeLayout" android:layout_width="match_parent" android:layout_height="200dp" android:background="@color/colorPrimary" android:orientation="horizontal"> <ImageView android:layout_width="120dp" android:layout_height="120dp" android:layout_centerHorizontal="true" android:layout_centerVertical="true" android:background="@drawable/ic_logo" /> </RelativeLayout> <ImageView android:id="@+id/imageView" android:layout_width="match_parent" android:layout_height="120dp" android:layout_below="@id/relativeLayout" android:layout_marginTop="-50dp" android:background="@drawable/waves" /> <RelativeLayout android:id="@+id/container" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_below="@id/imageView" android:orientation="vertical" android:padding="20dp"> <TextView android:id="@+id/textView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_marginTop="25dp" android:text="Wait for the code I sent You" android:textAppearance="@style/Base.TextAppearance.AppCompat.Headline" android:textColor="@color/colorPrimary" /> <ProgressBar android:id="@+id/progressbar" android:layout_below="@id/textView" android:layout_centerHorizontal="true" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <EditText android:id="@+id/editTextCode" android:layout_width="200dp" android:layout_height="wrap_content" android:layout_below="@id/progressbar" android:layout_centerHorizontal="true" android:layout_marginTop="10dp" android:digits="0123456789" android:drawablePadding="10dp" android:hint="enter verification code" android:inputType="phone" android:maxLength="10" /> <Button android:id="@+id/buttonSignIn" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/editTextCode" android:layout_centerHorizontal="true" android:layout_marginTop="15dp" android:background="@color/colorPrimaryDark" android:text="Sign In" android:textAllCaps="false" android:textColor="#cdd8f1" /> </RelativeLayout> </RelativeLayout> |
- Now we will create one more activity named ProfileActivity.
Creating ProfileActivity
- Create a new EmptyActivity named ProfileActivity and this activity will open after the successful login.
- In this screen we have nothing but only a TextView with a welcome message, as you can see below.
Getting the Mobile Number
- We will get the mobile number of the user in MainActivity. So come inside MainActivity.java and write the following code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
package net.simplifiedcoding.firebasephoneauthentication; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.EditText; public class MainActivity extends AppCompatActivity { private EditText editTextMobile; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); editTextMobile = findViewById(R.id.editTextMobile); findViewById(R.id.buttonContinue).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String mobile = editTextMobile.getText().toString().trim(); if(mobile.isEmpty() || mobile.length() < 10){ editTextMobile.setError("Enter a valid mobile"); editTextMobile.requestFocus(); return; } Intent intent = new Intent(MainActivity.this, VerifyPhoneActivity.class); intent.putExtra("mobile", mobile); startActivity(intent); } }); } } |
- The above code is very straightforward. We are just taking the mobile number from EditText and sending it to VerifyPhoneActivity.class with intent.
Verifying Mobile Number
Sending Verification Code
- For sending verification code we will use the following code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
private void sendVerificationCode(String mobile) { PhoneAuthProvider.getInstance().verifyPhoneNumber( "+91" + mobile, 60, TimeUnit.SECONDS, TaskExecutors.MAIN_THREAD, mCallbacks); } private PhoneAuthProvider.OnVerificationStateChangedCallbacks mCallbacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() { @Override public void onVerificationCompleted(PhoneAuthCredential phoneAuthCredential) { //Getting the code sent by SMS String code = phoneAuthCredential.getSmsCode(); //sometime the code is not detected automatically //in this case the code will be null //so user has to manually enter the code if (code != null) { editTextCode.setText(code); //verifying the code verifyVerificationCode(code); } } @Override public void onVerificationFailed(FirebaseException e) { Toast.makeText(VerifyPhoneActivity.this, e.getMessage(), Toast.LENGTH_LONG).show(); } @Override public void onCodeSent(String s, PhoneAuthProvider.ForceResendingToken forceResendingToken) { super.onCodeSent(s, forceResendingToken); mVerificationId = s; mResendToken = forceResendingToken; } }; |
- sendVerificationCode(): This method will send the verification code. You can also see that I am concatenating +91 with the mobile number which is the country code for India. But in real scenario you might have users from different countries. So if that is the case, you need to let the user select their country as well so that you know the code, and you can also tell the user to input the number with country code.
- mCallbacks: This is our callback that will help us to know the code is sent or not. It has three methods.
- onCodeSent(): This is called when the code is sent successfully. The first parameter here is our verification id that is sent. So we are storing it in our mVerificationId object.
- onVerificationFailed(): This method is called when the verification is failed for some reasons, so here we are only displaying a simple toast.
- onVerificationCompleted(): This method is called when the verification is completed. Here we have the PhoneAuthCredential Object which will give us the code if it is automatically detected.
Verifying Code and Sign In
- To verify verification code we will use this method. If the verification is successful we will let the user sign in into the application.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
private void verifyVerificationCode(String otp) { //creating the credential PhoneAuthCredential credential = PhoneAuthProvider.getCredential(mVerificationId, otp); //signing the user signInWithPhoneAuthCredential(credential); } private void signInWithPhoneAuthCredential(PhoneAuthCredential credential) { mAuth.signInWithCredential(credential) .addOnCompleteListener(VerifyPhoneActivity.this, new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if (task.isSuccessful()) { //verification successful we will start the profile activity Intent intent = new Intent(VerifyPhoneActivity.this, ProfileActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); startActivity(intent); } else { //verification unsuccessful.. display an error message String message = "Somthing is wrong, we will fix it soon..."; if (task.getException() instanceof FirebaseAuthInvalidCredentialsException) { message = "Invalid code entered..."; } Snackbar snackbar = Snackbar.make(findViewById(R.id.parent), message, Snackbar.LENGTH_LONG); snackbar.setAction("Dismiss", new View.OnClickListener() { @Override public void onClick(View v) { } }); snackbar.show(); } } }); } |
- Thats it, it will work. Now let me also show you the full code for VerifyPhoneActivity.java.
VerifyPhoneActivity Code
- Here is the full code of VerifyPhoneActivity.java I have also written comments to explain. But if you have any confusion, you can leave your comment below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 |
package net.simplifiedcoding.firebasephoneauthentication; import android.content.Intent; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.design.widget.Snackbar; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.EditText; import android.widget.Toast; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.android.gms.tasks.TaskExecutors; import com.google.firebase.FirebaseException; import com.google.firebase.auth.AuthResult; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseAuthInvalidCredentialsException; import com.google.firebase.auth.PhoneAuthCredential; import com.google.firebase.auth.PhoneAuthProvider; import java.util.concurrent.TimeUnit; public class VerifyPhoneActivity extends AppCompatActivity { //These are the objects needed //It is the verification id that will be sent to the user private String mVerificationId; //The edittext to input the code private EditText editTextCode; //firebase auth object private FirebaseAuth mAuth; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_verify_phone); //initializing objects mAuth = FirebaseAuth.getInstance(); editTextCode = findViewById(R.id.editTextCode); //getting mobile number from the previous activity //and sending the verification code to the number Intent intent = getIntent(); String mobile = intent.getStringExtra("mobile"); sendVerificationCode(mobile); //if the automatic sms detection did not work, user can also enter the code manually //so adding a click listener to the button findViewById(R.id.buttonSignIn).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String code = editTextCode.getText().toString().trim(); if (code.isEmpty() || code.length() < 6) { editTextCode.setError("Enter valid code"); editTextCode.requestFocus(); return; } //verifying the code entered manually verifyVerificationCode(code); } }); } //the method is sending verification code //the country id is concatenated //you can take the country id as user input as well private void sendVerificationCode(String mobile) { PhoneAuthProvider.getInstance().verifyPhoneNumber( "+91" + mobile, 60, TimeUnit.SECONDS, TaskExecutors.MAIN_THREAD, mCallbacks); } //the callback to detect the verification status private PhoneAuthProvider.OnVerificationStateChangedCallbacks mCallbacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() { @Override public void onVerificationCompleted(PhoneAuthCredential phoneAuthCredential) { //Getting the code sent by SMS String code = phoneAuthCredential.getSmsCode(); //sometime the code is not detected automatically //in this case the code will be null //so user has to manually enter the code if (code != null) { editTextCode.setText(code); //verifying the code verifyVerificationCode(code); } } @Override public void onVerificationFailed(FirebaseException e) { Toast.makeText(VerifyPhoneActivity.this, e.getMessage(), Toast.LENGTH_LONG).show(); } @Override public void onCodeSent(String s, PhoneAuthProvider.ForceResendingToken forceResendingToken) { super.onCodeSent(s, forceResendingToken); //storing the verification id that is sent to the user mVerificationId = s; } }; private void verifyVerificationCode(String code) { //creating the credential PhoneAuthCredential credential = PhoneAuthProvider.getCredential(mVerificationId, code); //signing the user signInWithPhoneAuthCredential(credential); } private void signInWithPhoneAuthCredential(PhoneAuthCredential credential) { mAuth.signInWithCredential(credential) .addOnCompleteListener(VerifyPhoneActivity.this, new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if (task.isSuccessful()) { //verification successful we will start the profile activity Intent intent = new Intent(VerifyPhoneActivity.this, ProfileActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); startActivity(intent); } else { //verification unsuccessful.. display an error message String message = "Somthing is wrong, we will fix it soon..."; if (task.getException() instanceof FirebaseAuthInvalidCredentialsException) { message = "Invalid code entered..."; } Snackbar snackbar = Snackbar.make(findViewById(R.id.parent), message, Snackbar.LENGTH_LONG); snackbar.setAction("Dismiss", new View.OnClickListener() { @Override public void onClick(View v) { } }); snackbar.show(); } } }); } } |
- Thats it now you can try running your application.
Firebase Phone Authentication Source Code
- Still having troubles? Don’t worry you can get my source code. Just unlock the link by subscribing to my youtube channel.
Firebase Phone Authentication Tutorial Source Code
So that’s all for this Firebase Phone Authentication Tutorial friends. I hope you found it useful, and if you really did then please help me by sharing this post will all your friends who are learning Android Application Development.
And for any question you can leave your comments here. Thank You 🙂