Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firebase Phone Authentication in flutter

I followed the flutter fire documentation for implementing the firebase phone auth. I tried this with the previous version of firebase_auth (firebase_auth:0.14.0+5) and everything seemed to work but I started a new app and installed the latest version of firebase_auth (firebase_auth:0.18.1+2) and anytime I call the firebase verifyNumber method my app carashes with this log :

E/zza     (12630): Problem retrieving SafetyNet Token: 7: 
D/ViewRootImpl@bab4cc4[MainActivity](12630): MSG_WINDOW_FOCUS_CHANGED 0
W/zzdq    (12630): keyset not found, will generate a new one
W/zzdq    (12630): java.io.FileNotFoundException: can't read keyset; the pref value GenericIdpKeyset does not exist
W/zzdq    (12630):  at com.google.android.gms.internal.firebase-auth-api.zzdv.zzc(com.google.firebase:firebase-auth@@20.0.0:13)
W/zzdq    (12630):  at com.google.android.gms.internal.firebase-auth-api.zzdv.zzb(com.google.firebase:firebase-auth@@20.0.0:32)
W/zzdq    (12630):  at com.google.android.gms.internal.firebase-auth-api.zzbd.zza(com.google.firebase:firebase-auth@@20.0.0:8)
W/zzdq    (12630):  at com.google.android.gms.internal.firebase-auth-api.zzdq$zza.zzd(com.google.firebase:firebase-auth@@20.0.0:73)
W/zzdq    (12630):  at com.google.android.gms.internal.firebase-auth-api.zzdq$zza.zzc(com.google.firebase:firebase-auth@@20.0.0:60)
W/zzdq    (12630):  at com.google.android.gms.internal.firebase-auth-api.zzdq$zza.zza(com.google.firebase:firebase-auth@@20.0.0:27)
W/zzdq    (12630):  at com.google.firebase.auth.internal.zzi.<init>(com.google.firebase:firebase-auth@@20.0.0:9)
W/zzdq    (12630):  at com.google.firebase.auth.internal.zzi.zza(com.google.firebase:firebase-auth@@20.0.0:17)
W/zzdq    (12630):  at com.google.firebase.auth.internal.RecaptchaActivity.zza(com.google.firebase:firebase-auth@@20.0.0:116)
W/zzdq    (12630):  at com.google.firebase.auth.api.internal.zzeq.<init>(com.google.firebase:firebase-auth@@20.0.0:14)
W/zzdq    (12630):  at com.google.firebase.auth.internal.RecaptchaActivity.onResume(com.google.firebase:firebase-auth@@20.0.0:78)
W/zzdq    (12630):  at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1277)
W/zzdq    (12630):  at android.app.Activity.performResume(Activity.java:7088)
W/zzdq    (12630):  at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3768)
W/zzdq    (12630):  at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3832)
W/zzdq    (12630):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2994)
W/zzdq    (12630):  at android.app.ActivityThread.-wrap14(ActivityThread.java)
W/zzdq    (12630):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1631)
W/zzdq    (12630):  at android.os.Handler.dispatchMessage(Handler.java:102)
W/zzdq    (12630):  at android.os.Looper.loop(Looper.java:154)
W/zzdq    (12630):  at android.app.ActivityThread.main(ActivityThread.java:6682)
W/zzdq    (12630):  at java.lang.reflect.Method.invoke(Native Method)
W/zzdq    (12630):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1520)
W/zzdq    (12630):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1410)
I/zzip    (12630): Provider GmsCore_OpenSSL not available
I/System.out(12630): (HTTPLog)-Static: isSBSettingEnabled false
I/System.out(12630): (HTTPLog)-Static: isSBSettingEnabled false
D/ViewRootImpl@9c9340d[RecaptchaActivity](12630): ThreadedRenderer.create() translucent=true
D/InputTransport(12630): Input channel constructed: fd=95
D/ViewRootImpl@9c9340d[RecaptchaActivity](12630): setView = DecorView@7954fc2[RecaptchaActivity] touchMode=true
D/ViewRootImpl@9c9340d[RecaptchaActivity](12630): dispatchAttachedToWindow
D/ViewRootImpl@9c9340d[RecaptchaActivity](12630): Relayout returned: oldFrame=[0,0][0,0] newFrame=[0,0][1440,2560] result=0x27 surface={isValid=true 501132826624} surfaceGenerationChanged=true
D/ViewRootImpl@9c9340d[RecaptchaActivity](12630): mHardwareRenderer.initialize() mSurface={isValid=true 501132826624} hwInitialized=true
D/mali_winsys(12630): EGLint new_window_surface(egl_winsys_display*, void*, EGLSurface, EGLConfig, egl_winsys_surface**, egl_color_buffer_format*, EGLBoolean) returns 0x3000,  [1440x2560]-format:1
D/ViewRootImpl@9c9340d[RecaptchaActivity](12630): MSG_RESIZED_REPORT: ci=Rect(0, 96 - 0, 0) vi=Rect(0, 96 - 0, 0) or=1
D/ViewRootImpl@9c9340d[RecaptchaActivity](12630): MSG_WINDOW_FOCUS_CHANGED 1
D/ViewRootImpl@9c9340d[RecaptchaActivity](12630): mHardwareRenderer.initializeIfNeeded()#2 mSurface={isValid=true 501132826624}
V/InputMethodManager(12630): Starting input: tba=android.view.inputmethod.EditorInfo@46ca60e nm : com.example.harpy ic=null
I/InputMethodManager(12630): [IMM] startInputInner - mService.startInputOrWindowGainedFocus
D/InputTransport(12630): Input channel constructed: fd=101
D/InputTransport(12630): Input channel destroyed: fd=93
W/IInputConnectionWrapper(12630): finishComposingText on inactive InputConnection
D/AndroidRuntime(12630): Shutting down VM
E/AndroidRuntime(12630): FATAL EXCEPTION: main
E/AndroidRuntime(12630): Process: com.example.harpy, PID: 12630
E/AndroidRuntime(12630): java.lang.NoClassDefFoundError: Failed resolution of: Landroidx/browser/customtabs/CustomTabsIntent$Builder;
E/AndroidRuntime(12630):    at com.google.firebase.auth.internal.RecaptchaActivity.zza(com.google.firebase:firebase-auth@@20.0.0:92)
E/AndroidRuntime(12630):    at com.google.firebase.auth.api.internal.zzeq.zza(com.google.firebase:firebase-auth@@20.0.0:79)
E/AndroidRuntime(12630):    at com.google.firebase.auth.api.internal.zzeq.onPostExecute(com.google.firebase:firebase-auth@@20.0.0:88)
E/AndroidRuntime(12630):    at android.os.AsyncTask.finish(AsyncTask.java:660)
E/AndroidRuntime(12630):    at android.os.AsyncTask.-wrap1(AsyncTask.java)
E/AndroidRuntime(12630):    at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:677)
E/AndroidRuntime(12630):    at android.os.Handler.dispatchMessage(Handler.java:102)
E/AndroidRuntime(12630):    at android.os.Looper.loop(Looper.java:154)
E/AndroidRuntime(12630):    at android.app.ActivityThread.main(ActivityThread.java:6682)
E/AndroidRuntime(12630):    at java.lang.reflect.Method.invoke(Native Method)
E/AndroidRuntime(12630):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1520)
E/AndroidRuntime(12630):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1410)
E/AndroidRuntime(12630): Caused by: java.lang.ClassNotFoundException: Didn't find class "androidx.browser.customtabs.CustomTabsIntent$Builder" on path: DexPathList[[zip file "/data/app/com.example.harpy-1/base.apk"],nativeLibraryDirectories=[/data/app/com.example.harpy-1/lib/arm64, /data/app/com.example.harpy-1/base.apk!/lib/arm64-v8a, /system/lib64, /vendor/lib64]]
E/AndroidRuntime(12630):    at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
E/AndroidRuntime(12630):    at java.lang.ClassLoader.loadClass(ClassLoader.java:380)
E/AndroidRuntime(12630):    at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
E/AndroidRuntime(12630):    ... 12 more
Lost connection to device.

What could possibly be the reason my app is crashing?

NOTE: I do not recieve the SMS

like image 773
Limitless Claver Avatar asked Oct 30 '20 04:10

Limitless Claver


People also ask

How do you implement a phone number verification by OTP using Firebase in Flutter?

Enable Phone Authentication in Firebase All you have to do is click enabled. Then download the google-services. json file again, and add it the project under android/app . Note: If you want to authenticate using email/password then check this tutorial: Using Firebase Auth In Flutter.

How to implement phone Auth singnin with Firebase in flutter?

I have implemented the phone auth singnIn with firebase in flutter its quite easy just import the firebase_auth library and validate the phone number is in proper format i.e it has a "+" sign in the beginning followed by country code then the phone number then the code goes like this

How to set up Firebase authentication?

Go to the Authentication section, go to the phone sign-in Provider, and enable it. You can also add a dummy phone number and OTP for testing purposes. Firebase auth provides us verifyPhoneNumber () to verify the phone number. FirebaseAuth. instance will create a firebase auth instance that will allow us to access various methods.

What is phone authentication in flutter?

Phone Authentication in Flutter. Building a phone number authentication… | by Anmol Gupta | FlutterDevs A uthenticating the user identity using the users mobile phone number is referred to as Phone Authentication.

How do I sign in with a phone number in flutterfire?

FlutterFire provides two individual ways to sign a user in with their phone number. Native (e.g. Android & iOS) platforms provide different functionality to validating a phone number than the web, therefore two methods exist for each platform exclusively: Native Platform: verifyPhoneNumber.


2 Answers

I got the same problem and solved it by updating latest packaged of flutter and android and I add SHA-1 and SHA-256 and used only flutter documentation methods then It starts working fine

like image 113
Azhar Ali Avatar answered Oct 05 '22 10:10

Azhar Ali


This is the code that works for me

import 'dart:async';

import 'package:cloud_functions/cloud_functions.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:harpy/providers/AuthenticationProvider.provider.dart';
import 'package:harpy/services/AuthRoute.service.dart';
import 'package:harpy/types/Response.type.dart';
import 'package:provider/provider.dart';

class AuthService{
  FirebaseAuth _firebaseAuth = FirebaseAuth.instance;
  final HttpsCallable createUser = CloudFunctions.instance.getHttpsCallable(functionName: 'createUser');
  String verificationId;
  AuthRoute _authRoute = AuthRoute();


  Future<void> validatePhoneNumberWithOTP(BuildContext context, String code) async{
    Provider.of<AuthenticationProvider>(context, listen: false).loading = true;
    // final AuthCredential authCredential = PhoneAuthProvider.getCredential(verificationId: this.verificationId, smsCode: code);
    final AuthCredential authCredential = PhoneAuthProvider.credential(verificationId: this.verificationId, smsCode: code);

    // final AuthResult _userCredential = await _firebaseAuth.signInWithCredential(authCredential);
    final UserCredential _userCredential = await _firebaseAuth.signInWithCredential(authCredential);
    Provider.of<AuthenticationProvider>(context, listen: false).loading = false;
    if(_userCredential.user != null){
      Provider.of<AuthenticationProvider>(context, listen: false).userIsVerified = true;
      //route here
    }else{
      Provider.of<AuthenticationProvider>(context, listen: false).userIsVerified = false;
      //TODO: show snackbar
      print("Enter the correct PIN");
    }

  }

  initAuth({BuildContext context, String phoneNumber}) async {
    Provider.of<AuthenticationProvider>(context, listen: false).loading = true;

    final PhoneVerificationCompleted verificationCompleted = (AuthCredential phoneAuthCredential) async {
      Provider.of<AuthenticationProvider>(context, listen: false).loading = true;
      // final AuthResult authResult = await _firebaseAuth.signInWithCredential(phoneAuthCredential);
      final UserCredential authResult = await _firebaseAuth.signInWithCredential(phoneAuthCredential);
      if(authResult.user != null){
        Provider.of<AuthenticationProvider>(context, listen: false).loading = false;
        Provider.of<AuthenticationProvider>(context, listen: false).userIsVerified = true;
      }
    };

    // final PhoneVerificationFailed verificationFailed = (AuthException authException) {
    final PhoneVerificationFailed verificationFailed = (FirebaseAuthException authException) {
      //TODO: handle verification failed exceptions
      print('Auth Exception is ${authException.message}');
    };

    final PhoneCodeSent codeSent = (String verificationId, [int forceResendingToken]) async {
      Provider.of<AuthenticationProvider>(context, listen: false).loading = false;
      Provider.of<AuthenticationProvider>(context, listen: false).codeSent = true;
      this.verificationId = verificationId;
    };

    final PhoneCodeAutoRetrievalTimeout codeAutoRetrievalTimeout = (String verificationId) {
      //TODO: handle timeouts
      this.verificationId = verificationId;
    };

    await _firebaseAuth.verifyPhoneNumber(
        phoneNumber: phoneNumber,
        verificationCompleted: verificationCompleted,
        verificationFailed: verificationFailed,
        codeSent: codeSent,
        codeAutoRetrievalTimeout: codeAutoRetrievalTimeout,
        timeout: Duration(seconds: 60)
    );

  }

  Future<Response> updateUserprofile({context, String name,String email}) async{

    User _user = _firebaseAuth.currentUser;
    Response response = Response(success: false);
    Provider.of<AuthenticationProvider>(context, listen: false).loading = true;

    try{

      HttpsCallableResult functionResponse  = await createUser.call({'displayName': name, 'email':email, 'phoneNumber': _user.phoneNumber});
      response.success = functionResponse.data['success'];
      response.message = functionResponse.data['message'];

      _user.updateProfile(displayName: name);
      // _user.updateEmail(email);

      AuthCredential credential = AuthCredential(providerId: PhoneAuthProvider.PROVIDER_ID, signInMethod: PhoneAuthProvider.PHONE_SIGN_IN_METHOD);
      await _user.reauthenticateWithCredential(credential);

      _user.reload();

      Provider.of<AuthenticationProvider>(context, listen: false).loading = false;

      return response;
    }catch(e){
      Provider.of<AuthenticationProvider>(context, listen: false).loading = false;
      response.message = e.message;
      return response;
    }
  }

  signOut(BuildContext context) async{
    await _firebaseAuth.signOut();
    _authRoute.route(context);
  }
}

like image 25
Limitless Claver Avatar answered Oct 05 '22 08:10

Limitless Claver