Adding Firebase phone authentication in Flutter and removing reCAPTCHA for authentication

Firebase provides a variety of tools at one place to nourish your app such as authentication of users, cloud storage, cloud database, deep analytics of the app etc.

So, among these services we’ll be using phone authentication service provided by firebase and will remove the reCAPTCHA screen. So, without wasting any time let’s proceed.

Setup

Before proceeding further you need to initiate the steps mentioned below:-

  1. Create a Flutter project
  2. Create a Firebase project
  3. Link the Flutter app to Firebase

In case you find difficulties in above steps, refer to the official documentations for Understanding Firebase projects and Add Firebase to your Flutter App. After doing so remember to add SHA-256 fingerprint by going to project settings in Firebase console. For getting SHA-256 you can follow official documentation or simply open the android folder of your flutter project in terminal and run “gradlew signingReport”. This will generate SHA fingerprints which you can add in the project..

After this open the Firebase Console and on the left side you’ll find a menu and search for “Authentication” which will be present under the ‘Build’. In authentication choose “Sign-In method”. Enable Phone Authentication by clicking on toggle button to enable and after enabling simply save it.

Enabling phone authentication in Firebase Console

Now add the following dependences in your pubspec.yaml file and run flutter pub get.

After, getting the above required dependencies we need to initialize the firebase app, so let’s go to the main.dart file and add the following code:-

Now let’s work on phone authentication

So, our SignIn page consists of 2 screens i.e. first one to allow user to enter phone number and second one to enter OTP..

Before proceeding with the UI and the authentication, let’s declare all the variables in SignIn widget which will be used throughout:-

Screen for entering phone number

For phone verification the country code is required so for that we are using the intl_phone_number_input. This dependency allows user to pick his/her country code and also takes care of phone digit verification.

Phone Number field

Now since we have created the UI to receive phone number with country code as an input from the user. We will now create the Get OTP button. These two designs are in column which is further wrapped with Form to validate the number. For clarity will be sharing the GitHub repo link at the bottom of the story.

The get OTP button triggers the verifyPhoneNumber function which is responsible to verify and send OTP on your device. The function consists of the following try catch block to verify the number

You can see there are various functions/callbacks in the above code. Let’s try to understand them step by step:-

  1. The very first thing phoneNumber, asks for the number which is to be verified. So, over here we have passed the phone number received from the user.
  2. The second is timeout, which is the maximum amount of time you are willing to wait for SMS auto-retrieval to be completed by the library. Maximum allowed value is 2 minutes.
  3. The third is forceResendingToken, it is responsible for resending the OTP before code auto retrieval time out has occurred. Here we are checking whether the previously declared variable forceResendingToken is null or not. As for first time it will be null so no need to pass token and when you want to resend OTP then you need to pass this token to the parameter. This token will be received in the codeSent callback which is explained in the step 6.
  4. The fourth is verificationCompleted, On some devices we don’t need to enter OTP. So, this is called when the phone number is automatically verified and therefore you can simply log the user in with the credentials received.
  5. The fifth is verificationFailed, this is called when an error has occurred while verifying the number. You can know about the error by using FirebaseAuthException.
  6. The sixth is codeSent, this is called when the OTP is successfully sent to the user device. This callback contains verificationId which is used to get the user credential for signing in and the forceResendingToken which is used to resend the OTP. These values are stored in the variables declared previously.
  7. The seventh is codeAutoRetrievalTimeout, this is called when SMS auto-retrieval times out and provide a verificationId.
Screen for entering OTP

After the above events we will set the variable showOtpScreen to true, to show the otpScreen. We gonna use the plugin pin_code_fields to get the desired UI for entering the OTP.

UI for entering the OTP received

In the above code I have wrapped the PinCodeTextField with AbsorbPointer so the default keyboard doesn’t popup when user tap on these blocks as I am using the custom keyboard design. In case you don’t need such design and want the native keyboard to be shown then just remove AbosrbPointer from the above code.

From the above code you can see that when user taps on Code not received? then also we are calling the verifyPhoneNumber() function. The reason is that this time we have forceResendingToken received in Step 6, which will be passed this time to again send OTP and verify the phone number.

Now let’s create the OK button to sign in with the phone number.

As you can see in the above code that we are calling the function signInWithPhoneNumber to sign the user by the OTP received. In this function we gonna pass the verificationId received in Step 6 and the otp entered by the user to get the AuthCredential which will further passed to signinWithCredentital to get the user. On receiving the id you can store the data in backend(if required) and navigate to the home screen.

After calling and successful execution of the above function you’ll be redirected to the homescreen which will display the new user id.

Home Screen

Removing reCAPTCHA Screen

While running the above code you might have seen the following screens which are shown before receiving OTP.

In Order to remove this reCAPTCHA you need to add SHA-256 fingerprint in your firebase project settings as mentioned in the Setup section of this story. After that again navigate to your firebase project settings and click on “App Check” .

Click on Settings icon and select project settings

Select app check from project settings

In the overview of the App Check section you’ll see that in front of your app name the status is shown as ‘Unregistered’. So, simply tap on your app name and then click on Safety Net. It will expand the layout, now add SHA-256(if not added previously) and agree to the terms and conditions by checking the checkbox and save it.

Enabling Safety Net

Boom! Now your app status under overview will be updated to “Registered” and reCAPTCHA screen will removed from your app.
Note:- If you are testing phone authentication on an emulator then reCAPTCHA screen will be still shown but for real devices it won’t be shown anymore as stated in the official documentation:-
In the event that SafetyNet cannot be used, such as when the user does not have Google Play Services support, or when testing your app on an emulator, Firebase Authentication uses a reCAPTCHA verification to complete the phone sign-in flow.

Preparing for Release:-In case you are preparing your app for release mode then you need to add SHA fingerprints (present in the playstore) to your firebase project settings.

Conclusion

Congratulations!! You have successfully learned how to add phone authentication in Flutter using Firebase and remove reCAPTCHA from phone authentication. In case you need the whole code then you can check it out at my GitHub repo:-
https://github.com/deepaklohmod6789/phone_auth

Comments

Popular posts from this blog

Accept Payments in Flutter App and Website with Razorpay: 2 Ways to Auto-Capture Payments

Top 5 tips for flutter performance optimization and following best practices to build your next project.