Overview
In this era of mobile application development, Authentication is a basic need of every application in the market, there are many types of authentication like Facebook login, email login, phone number OTP verification available using firebase in android. In this blog, we will learn phone numbers with OTP verification with firebase. With firebase phone number authentication use will get OTP(one-time password) through SMS to sign in.
Topics
- Connect your app to firebase.
- Enable phone authentication in firebase.
- Add Dependencies in your project.
- Design your XML related to your project.
- Send verification code to the user
- Verify OTP and signIn.
Above mentioned the steps are for firebase phone number OTP authentication. All are described properly below.
Connect your app to firebase
First of all, click on tools in the top app bar of your android studio and then click on firebase. Then you can see a new window open on the right side of the studio. Then click on authentication and then click on authentication using google sign-in.so, your app is connecting to firebase and your project will be seen in firebase.
Enable Phone Authentication in firebase.
After successfully connecting your app with firebase, open your project in the console then go to the authentication on your left side window in the console. Then click on the sign-in method. Then click on the phone and enable it.And last save it.
Add Dependencies to your Project.
After enabling the phone in the firebase console. Make sure to add the following dependencies in your build.gradle file. After adding dependencies sync your project.
implementation platform('com.google.firebase:firebase-bom:28.1.0') implementation 'com.google.firebase:firebase-auth-ktx'
Design your XML related to your Project.
Now, let’s start with the basic design with two edit text and with two buttons. First, edit text for the Enter Mobile Number and first button for generate OTP. Second edit text for the Enter Received OTP and second button for the verify OTP.
<?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout 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" android:padding="10dp" tools:context=".MainActivity"> <TextView android:id="@+id/tv_demo" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/firebase_otp" android:textSize="35sp" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" /> <com.google.android.material.textfield.TextInputEditText android:id="@+id/et_phone_num" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_marginTop="10dp" android:hint="@string/enter_mobile_number" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@id/tv_demo" /> <com.google.android.material.button.MaterialButton android:id="@+id/btn_generate_otp" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/send_otp" android:textSize="15sp" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@id/et_phone_num" /> <com.google.android.material.textfield.TextInputEditText android:id="@+id/et_enter_otp" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_marginTop="15dp" android:hint="@string/enter_received_otp" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@id/btn_generate_otp" /> <com.google.android.material.button.MaterialButton android:id="@+id/btn_verify_otp" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="10dp" android:text="@string/verify_otp" android:textSize="15sp" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@id/et_enter_otp" /> </androidx.constraintlayout.widget.ConstraintLayout>
Send verification code to the user.
After completing the design. When the user enters a number and clicks on send OTP then the below code is useful for sending verification code. So In the Kotlin file, the code is as per below.
btn_generate_otp.setOnClickListener { if (et_phone_num.text.toString().length == 10) { FirebaseAuth.getInstance().addAuthStateListener { val options = PhoneAuthOptions.newBuilder(it)// it-> firebase auth token. .setPhoneNumber("+91" + et_phone_num.text.toString()) .setTimeout(60L, TimeUnit.SECONDS) // Timeout and unit .setActivity(this)// Activity (for callback binding) .setCallbacks(object : PhoneAuthProvider.OnVerificationStateChangedCallbacks(){ override fun onVerificationCompleted(p0: PhoneAuthCredential){ Toast.makeText(applicationContext, "completed", Toast.LENGTH_SHORT ).show() } override fun onVerificationFailed(p0: FirebaseException){ Toast.makeText(applicationContext, "failed", Toast.LENGTH_SHORT ).show() } override fun onCodeSent( otp: String, // this is the otp which is send by firebase token: PhoneAuthProvider.ForceResendingToken ) { sendOtp = otp // i store this in one global variable Toast.makeText( applicationContext, "otp send successfully", Toast.LENGTH_SHORT ).show() } }).build() PhoneAuthProvider.verifyPhoneNumber(options) } } else { Toast.makeText( applicationContext, "Mobile number must be 10 Digit", Toast.LENGTH_SHORT ).show() } }
In the above code, there are basically three callbacks. OnVerificationCompleted, OnVerificationFailed, OnCodeSent.
- onVerificationCompleted : This method is called when the user is verified without the use of code automatically or Code is null and verified on its own.
- onVerificationFailed : This method is called when the verification fails due to any reason like phone number format error or etc.
- onCodeSent : This method is called when the SMS is sent to the entered number.
Verify OTP and Sign-in.
Now, For verifying the OTP user can match the send OTP with the entered OTP which is entered by the user in edit text. So for verifying bellow code is used.
btn_verify_otp.setOnClickListener { if (et_enter_otp.text.toString().length == 6) { val enterOtp = et_enter_otp.text.toString() val credential=PhoneAuthProvider.getCredential(sendOtp,enterOtp) //sendOtp is taken from the onCodeSent Method. FirebaseAuth.getInstance().signInWithCredential(credential) .addOnCompleteListener(this) { task -> if (task.isSuccessful) { Toast.makeText( applicationContext, "login successful", Toast.LENGTH_SHORT ).show() startActivity( Intent( this, DashboardActivity::class.java //in dash )) //Dashboard activity is for sign in purpose. } else { Toast.makeText( applicationContext, "wrong otp", Toast.LENGTH_SHORT ).show() } } } else { Toast.makeText( applicationContext, "Otp must be 6 digits", Toast.LENGTH_SHORT).show() } } }
Limitations of OTP in firebase:
From the use of firebase OTP verification using a phone number is FREE. The free plan of firebase has Ten Thousand Verification per month, but if you exceed this limit, you need to pay for that.
Conclusion
These steps and the whole approach are helpful for many users to do authentication in an easy way and also easy to understand.
All the source code is available Firebase Otp Authentication at this GitHub Repo.
Thanks for reading this blog. I hope this is useful to you all.