flutterfirebasefirebase-authentication

Firebase authentication using OTP


I'm working on flutter taxi app.

When trying to send an OTP code, I faced this error:

[SmsRetrieverHelper] SMS verification code request failed: unknown status code: 17028 Invalid app info in play_integrity_token
D/FirebaseAuth(19555): Invoking original failure callbacks after phone verification failure for +970 569292492, error - This app is not authorized to use Firebase Authentication. Please verify that the correct package name, SHA-1, and SHA-256 are configured in the Firebase Console. [ Invalid app info in play_integrity_token ]
E/flutter (19555): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: [firebase_auth/app-not-authorized] This app is not authorized to use Firebase Authentication. Please verify that the correct package name, SHA-1, and SHA-256 are configured in the Firebase Console. [ Invalid app info in play_integrity_token ]
E/flutter (19555): #0      AuthServices.loginWithOTP.<anonymous closure> (package:taxi_driver/Services/AuthService.dart:206:11)
E/flutter (19555): #1      MethodChannelFirebaseAuth.verifyPhoneNumber.<anonymous closure> (package:firebase_auth_platform_interface/src/method_channel/method_channel_firebase_auth.dart:631:29)
E/flutter (19555): #2      _RootZone.runUnaryGuarded (dart:async/zone.dart:1594:10)
E/flutter (19555): #3      _BufferingStreamSubscription._sendData (dart:async/stream_impl.dart:365:11)
E/flutter (19555): #4      _BufferingStreamSubscription._add (dart:async/stream_impl.dart:297:7)
E/flutter (19555): #5      _ForwardingStreamSubscription._add (dart:async/stream_pipe.dart:123:11)
E/flutter (19555): #6      _HandleErrorStream._handleData (dart:async/stream_pipe.dart:253:10)
E/flutter (19555): #7      _ForwardingStreamSubscription._handleData (dart:async/stream_pipe.dart:153:13)
E/flutter (19555): #8      _RootZone.runUnaryGuarded (dart:async/zone.dart:1594:10)
E/flutter (19555): #9      _BufferingStreamSubscription._sendData (dart:async/stream_impl.dart:365:11)
E/flutter (19555): #10     _DelayedData.perform (dart:async/stream_impl.dart:541:14)
E/flutter (19555): #11     _PendingEvents.handleNext (dart:async/stream_impl.dart:646:11)
E/flutter (19555): #12     _PendingEvents.schedule.<anonymous closure> (dart:async/stream_impl.dart:617:7)
E/flutter (19555): #13     _microtaskLoop (dart:async/schedule_microtask.dart:40:21)
E/flutter (19555): #14     _startMicrotaskLoop (dart:async/schedule_microtask.dart:49:5)
E/flutter (19555): 

I added both of SHA-1 and SHA-256 to my firebase app like this:

Firebase app SHA certificate fingerprints

Notifications works good in the app.

This is my firebase initialize:

await Firebase.initializeApp(
    options: const FirebaseOptions(
      apiKey: 'AIzaSyCPeRJrJwY6u78FjKsAyxk9VUTRZ_Gn6Q4',
      appId: '1:211011031878:android:616945e871967f09084b47',
      messagingSenderId: '211011031878',
      projectId: 'classystore-b84cd',
      storageBucket: 'classystore-b84cd.appspot.com',
    ),
  ).then((value) {
    FlutterError.onError = FirebaseCrashlytics.instance.recordFlutterError;
  });

And here is my android/build.gradle:

buildscript {
//    ext.kotlin_version = '1.8.20'
    repositories {
        google()
        mavenCentral()
    }

    dependencies {
        classpath 'com.android.tools.build:gradle:7.4.2'
//        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        classpath 'com.google.gms:google-services:4.4.2'
    }
}

allprojects {
    repositories {
        google()
        mavenCentral()
    }
}

rootProject.buildDir = '../build'
subprojects {
    project.buildDir = "${rootProject.buildDir}/${project.name}"
}
subprojects {
    project.evaluationDependsOn(':app')
}

tasks.register("clean", Delete) {
    delete rootProject.buildDir
}

And here is my android/app/build.gradle:

plugins {
    id "com.android.application"
    id "kotlin-android"
    id "dev.flutter.flutter-gradle-plugin"
    id "com.google.gms.google-services"
}


def localProperties = new Properties()
def localPropertiesFile = rootProject.file('local.properties')
if (localPropertiesFile.exists()) {
    localPropertiesFile.withReader('UTF-8') { reader ->
        localProperties.load(reader)
    }
}

def flutterRoot = localProperties.getProperty('flutter.sdk')
if (flutterRoot == null) {
    throw new GradleException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.")
}


//apply plugin: 'com.android.application'
//apply plugin: 'kotlin-android'
//apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"
//apply plugin: 'com.google.gms.google-services'

android {
    compileSdkVersion 34

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_11
        targetCompatibility JavaVersion.VERSION_11
    }

    kotlinOptions {
        jvmTarget = '1.8'
    }

    sourceSets {
        main.java.srcDirs += 'src/main/kotlin'
    }

    defaultConfig {
        applicationId "com.mighty.taxidriver"
        minSdkVersion 23
        targetSdkVersion 34
        versionCode 17
        versionName '2.2.1'
    }

    buildTypes {
        release {
            signingConfig signingConfigs.debug
            minifyEnabled false
            shrinkResources false
        }
    }
    buildToolsVersion '29.0.3'
}

flutter {
    source '../..'
}

dependencies {
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:1.8.10"
    implementation platform('com.google.firebase:firebase-bom:33.1.2')
    implementation 'androidx.multidex:multidex:2.0.1'
//    implementation 'com.mercadopago.android.px:checkout:4.+'
    implementation('com.braintreepayments.api:drop-in:5.2.1'){
        exclude group: "org.jfrog.cardinalcommerce.gradle", module: "cardinalmobilesdk"
    }
    implementation("org.jfrog.cardinalcommerce.gradle:cardinalmobilesdk:2.2.7-2")
}

And this is the code of login OTP:

Future<void> loginWithOTP(BuildContext context, String phoneNumber) async {
    return await _auth.verifyPhoneNumber(
      phoneNumber: phoneNumber,
      verificationCompleted: (PhoneAuthCredential credential) async {},
      verificationFailed: (FirebaseAuthException e) {
        if (e.code == 'invalid-phone-number') {
          toast('The provided phone number is not valid.');
          throw 'The provided phone number is not valid.';
        } else {
          toast(e.toString());
          throw e.toString();
        }
      },
      codeSent: (String verificationId, int? resendToken) async {
        Navigator.pop(context);
        appStore.setLoading(false);
        await showDialog(
          context: context,
          builder: (context) => AlertDialog(content: OTPDialog(verificationId: verificationId, isCodeSent: true, phoneNumber: phoneNumber)),
          barrierDismissible: false,
        );
      },
      codeAutoRetrievalTimeout: (String verificationId) {
        //
      },
    );
  }

I'm trying to send an OTP code to the driver's phone to let driver access the app. The OTP code should arrive at the driver's phone.


Solution

  • As i can see the error arises due to integrity token.So make sure you have added this

    await FirebaseAppCheck.instance.activate(
        androidProvider: AndroidProvider.playIntegrity,
        appleProvider: AppleProvider.appAttest
      );
    

    If still error then first try removing enforcement from Appcheck in firebase. If error resolves : need rebuild If error exist: check for SHA and package name in firebase