Phone Number Authentication Using Firebase

In this article, I am going to explain how to use phone number authentication on Android with Google firebase, which allows users to sign in using their phone number by receiving a One Time Password SMS.

Firebase


Firebase is a backend tool for mobile and web applications.

It offers Analytics, Cloud Messaging, Real-time Database, Storage, Remote Configuration, Notification, Crash Reporting, API’s, Multiple Authentication types, Hosting, Dynamic Links and Invites.

Google Firebase helps to develop the Application rapidly.

 

Requirements

  • Android Studio.
  • Google Account.

Follow the steps given below to build an Android application

Open an Android Studio and create a new project.

Login to Google Firebase and create a new project in console.

 

After creating the project select “Add Firebase to your Android app” in Firebase overview page.

 

After adding an Application, give your Android application package name, App nickname and Debug signing certificate SHA-1 hit REGISTERAPP.

 

Now, download Google-services.json file add into your application; app folder.

Adding Dependencies

Add the dependencies plug-in in App gradle for firebase phone authentication.

  1. compile 'com.google.firebase:firebase-auth:11.0.4'  
Add Gradle plug-in (build.gradle(app)) end of the code.
  1. apply plugin: 'com.google.gms.google-services'  
Add classpath plug-in in project gradle
  1. classpath 'com.google.gms:google-services:3.1.0'  

Enable Phone Number sign-in for your Firebase project

In the Firebase console, open the Authentication section.

 

On the Sign-in Method page, enable the Phone Number sign-in method.

Now, go to Android Studio and copy the code.

Creating Layout

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     xmlns:tools="http://schemas.android.com/tools"  
  4.     android:id="@+id/activity_main"  
  5.     android:layout_width="match_parent"  
  6.     android:layout_height="match_parent"  
  7.     android:orientation="vertical"  
  8.     android:paddingBottom="@dimen/activity_vertical_margin"  
  9.     android:paddingLeft="@dimen/activity_horizontal_margin"  
  10.     android:paddingRight="@dimen/activity_horizontal_margin"  
  11.     android:paddingTop="@dimen/activity_vertical_margin"  
  12.     tools:context="io.github.saravanan_selvaraju.phoneauthentication.MainActivity">  
  13.     <EditText  
  14.         android:layout_width="match_parent"  
  15.         android:layout_height="wrap_content"  
  16.         android:hint="Phone Number"  
  17.         android:inputType="phone"  
  18.         android:padding="15dp"  
  19.         android:maxLength="10"  
  20.         android:id="@+id/phone"/>  
  21.     <EditText  
  22.         android:layout_width="match_parent"  
  23.         android:layout_height="wrap_content"  
  24.         android:padding="15dp"  
  25.         android:id="@+id/code"  
  26.         android:hint="Verification Code"  
  27.         android:visibility="gone"/>  
  28.     <Button  
  29.         android:layout_width="match_parent"  
  30.         android:layout_height="wrap_content"  
  31.         android:text="Verify"  
  32.         android:layout_below="@+id/phone"  
  33.         android:id="@+id/getcode"  
  34.         android:padding="15dp"  
  35.         android:onClick="GetCode"/>  
  36.     <Button  
  37.         android:layout_width="match_parent"  
  38.         android:layout_height="wrap_content"  
  39.         android:id="@+id/verify"  
  40.         android:layout_below="@+id/code"  
  41.         android:text="Verify"  
  42.         android:onClick="verify"  
  43.         android:padding="15dp"  
  44.         android:visibility="gone"/>  
  45.     <TextView  
  46.         android:layout_width="match_parent"  
  47.         android:layout_height="wrap_content"  
  48.         android:gravity="center"  
  49.         android:id="@+id/msgtxt"  
  50.         android:layout_centerInParent="true"  
  51.         android:text="Signin Successfully"  
  52.         android:padding="5dp"  
  53.         android:textColor="#000000"  
  54.         android:visibility="gone"/>  
  55. </RelativeLayout>  

Creating Activity

  1. package io.github.saravanan_selvaraju.phoneauthentication;  
  2.   
  3. import android.content.Intent;  
  4. import android.support.annotation.NonNull;  
  5. import android.support.v7.app.AppCompatActivity;  
  6. import android.os.Bundle;  
  7. import android.util.Log;  
  8. import android.view.View;  
  9. import android.widget.Button;  
  10. import android.widget.EditText;  
  11. import android.widget.TextView;  
  12. import android.widget.Toast;  
  13.   
  14. import com.google.android.gms.tasks.OnCompleteListener;  
  15. import com.google.android.gms.tasks.Task;  
  16. import com.google.firebase.FirebaseException;  
  17. import com.google.firebase.FirebaseTooManyRequestsException;  
  18. import com.google.firebase.auth.*;  
  19. import java.util.concurrent.TimeUnit;  
  20.   
  21. public class MainActivity extends AppCompatActivity {  
  22.     EditText phone,vcode;  
  23.     TextView msg;  
  24.     Button getcode,verify;  
  25.     private FirebaseAuth mAuth;  
  26.     private String mVerificationId;  
  27.     private PhoneAuthProvider.ForceResendingToken mResendToken;  
  28.     private PhoneAuthProvider.OnVerificationStateChangedCallbacks mCallbacks;  
  29.     @Override  
  30.     protected void onCreate(Bundle savedInstanceState) {  
  31.         super.onCreate(savedInstanceState);  
  32.         setContentView(R.layout.activity_main);  
  33.         phone = (EditText) findViewById(R.id.phone);  
  34.         vcode = (EditText) findViewById(R.id.code);  
  35.         getcode=(Button)findViewById(R.id.getcode);  
  36.         verify=(Button)findViewById(R.id.verify);  
  37.         msg=(TextView)findViewById(R.id.msgtxt);  
  38.         mAuth = FirebaseAuth.getInstance();  
  39.         mCallbacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {  
  40.   
  41.             @Override  
  42.             public void onVerificationCompleted(PhoneAuthCredential credential) {  
  43.                 Toast.makeText(MainActivity.this,"Verified",Toast.LENGTH_LONG).show();  
  44.                 vcode.setVisibility(View.GONE);  
  45.                 verify.setVisibility(View.GONE);  
  46.                 msg.setVisibility(View.VISIBLE);  
  47.             }  
  48.   
  49.             @Override  
  50.             public void onVerificationFailed(FirebaseException e) {  
  51.                 Toast.makeText(MainActivity.this,"Login Faled",Toast.LENGTH_LONG).show();  
  52.   
  53.                 if (e instanceof FirebaseAuthInvalidCredentialsException) {  
  54.                     // Invalid request  
  55.                     // ...  
  56.                 } else if (e instanceof FirebaseTooManyRequestsException) {  
  57.                     // The SMS quota for the project has been exceeded  
  58.                 }  
  59.   
  60.             }  
  61.   
  62.             @Override  
  63.             public void onCodeSent(String verificationId,  
  64.                                    PhoneAuthProvider.ForceResendingToken token) {  
  65.   
  66.                 mVerificationId = verificationId;  
  67.                 mResendToken = token;  
  68.   
  69.             }  
  70.         };  
  71.   
  72.   
  73.     }  
  74.   
  75.     public void GetCode(View view) {  
  76.         PhoneAuthProvider.getInstance().verifyPhoneNumber(  
  77.                 phone.getText().toString(),  
  78.                 60,  
  79.                 TimeUnit.SECONDS,  
  80.                 this,  
  81.                 mCallbacks);  
  82.         phone.setVisibility(View.GONE);  
  83.         getcode.setVisibility(View.GONE);  
  84.         vcode.setVisibility(View.VISIBLE);  
  85.         verify.setVisibility(View.VISIBLE);  
  86.   
  87.     }  
  88.   
  89.     public void verfy(View view) {  
  90.   
  91.             PhoneAuthCredential credential = PhoneAuthProvider.getCredential(mVerificationId, vcode.getText().toString());  
  92.             signInWithPhoneAuthCredential(credential);  
  93.         }  
  94.     private void signInWithPhoneAuthCredential(PhoneAuthCredential credential) {  
  95.         mAuth.signInWithCredential(credential)  
  96.                 .addOnCompleteListener(thisnew OnCompleteListener<AuthResult>() {  
  97.                     @Override  
  98.                     public void onComplete(@NonNull Task<AuthResult> task) {  
  99.                         if (task.isSuccessful()) {  
  100.                             vcode.setVisibility(View.GONE);  
  101.                             verify.setVisibility(View.GONE);  
  102.                             msg.setVisibility(View.VISIBLE);  
  103.                         } else {  
  104.                             if (task.getException() instanceof FirebaseAuthInvalidCredentialsException) {  
  105.                                 Toast.makeText(MainActivity.this,"Invslid code",Toast.LENGTH_LONG).show();  
  106.                                 }  
  107.                             }  
  108.                     }  
  109.                 });  
  110.     }  
  111. }  

Please don’t forgot to add internet access permission on androidmanifest.xml

  1. <uses-permission android:name="android.permission.INTERNET" />  

Now, run your application.

Sample output

 
 
   

Summary

In this article, we discussed about what Google Firebase is, and how to use phone number authentication on Android app with firebase authentication.

Up Next
    Ebook Download
    View all
    Learn
    View all