invertase / react-native-firebase

🔥 A well-tested feature-rich modular Firebase implementation for React Native. Supports both iOS & Android platforms for all Firebase services.
https://rnfirebase.io
Other
11.64k stars 2.21k forks source link

🔥 NativeFirebaseError: [auth/invalid-app-credential] Invalid token. #4983

Closed Vadko closed 3 years ago

Vadko commented 3 years ago

Issue

Getting following error when trying to use signInWithPhoneNumber() : [auth/invalid-app-credential] Invalid token. Tried to upload APNs Authentication Key and it didn't help and then tried to use APNs Certificates (as described here https://github.com/invertase/react-native-firebase/issues/3183#issue-561966302), it didn't help also.

Project Files

Javascript

Click To Expand

#### `package.json`: ``` { "name": "skye2", "version": "0.0.1", "private": true, "scripts": { "android": "react-native run-android", "ios": "react-native run-ios", "start": "react-native start", "test": "jest", "lint": "eslint ." }, "dependencies": { "@react-native-community/async-storage": "^1.12.1", "@react-native-community/datetimepicker": "^3.0.9", "@react-native-community/masked-view": "^0.1.10", "@react-native-firebase/analytics": "^10.8.1", "@react-native-firebase/app": "^10.8.1", "@react-native-firebase/auth": "^10.8.1", "@react-native-firebase/firestore": "^10.8.1", "@react-native-firebase/functions": "^10.8.1", "@react-native-firebase/messaging": "^10.8.1", "@react-native-picker/picker": "^1.9.11", "@react-navigation/native": "^5.9.3", "@react-navigation/stack": "^5.14.3", "@typescript-eslint/eslint-plugin": "^4.16.0", "@typescript-eslint/parser": "^4.16.0", "add": "^2.0.6", "dayjs": "^1.10.4", "eslint-config-universe": "^7.0.1", "lottie-react-native": "^3.5.0", "moment": "^2.29.1", "react": "16.13.1", "react-hook-form": "^6.15.4", "react-native": "0.63.4", "react-native-confirmation-code-field": "^6.5.1", "react-native-fbsdk": "^3.0.0", "react-native-flash-message": "^0.1.23", "react-native-gesture-handler": "^1.10.3", "react-native-modal-datetime-picker": "^9.2.0", "react-native-picker-select": "^8.0.4", "react-native-reanimated": "^1.13.2", "react-native-responsive-screen": "^1.4.2", "react-native-safe-area-context": "^3.1.9", "react-native-screens": "^2.18.1", "react-native-snap-carousel": "^3.9.1", "react-native-text-input-mask": "^2.0.1", "react-native-toast-message": "^1.4.7", "react-native-vector-icons": "^8.1.0", "react-redux": "^7.2.2", "react-redux-firebase": "^3.10.0", "react-spring": "^8.0.27", "redux": "^4.0.5", "redux-firestore": "^0.15.0", "redux-persist": "^6.0.0", "typescript": "^4.2.2", "yarn": "^1.22.10" }, "devDependencies": { "@babel/core": "^7.8.4", "@babel/runtime": "^7.13.9", "@react-native-community/eslint-config": "^1.1.0", "babel-jest": "^25.1.0", "eslint": "^6.5.1", "jest": "^25.1.0", "metro-react-native-babel-preset": "^0.59.0", "react-test-renderer": "16.13.1" }, "eslintConfig": { "extends": "universe/native" }, "jest": { "preset": "react-native" } } ``` ```json # N/A ``` #### `firebase.json` for react-native-firebase v6: ```json # N/A ```

iOS

Click To Expand

#### `ios/Podfile`: - [ ] I'm not using Pods - [x] I'm using Pods and my Podfile looks like: ``` require_relative '../node_modules/react-native/scripts/react_native_pods' require_relative '../node_modules/@react-native-community/cli-platform-ios/native_modules' platform :ios, '10.0' target 'skye2' do config = use_native_modules! use_react_native!(:path => config["reactNativePath"]) pod 'RNInputMask', :path => '../node_modules/react-native-text-input-mask/ios/InputMask' pod 'RNVectorIcons', :path => '../node_modules/react-native-vector-icons' target 'skye2Tests' do inherit! :complete # Pods for testing end # Enables Flipper. # # Note that if you have use_frameworks! enabled, Flipper will not work and # you should disable these next few lines. use_flipper! post_install do |installer| flipper_post_install(installer) end end target 'skye2-tvOS' do # Pods for skye2-tvOS target 'skye2-tvOSTests' do inherit! :search_paths # Pods for testing end end ``` ```ruby # N/A ``` #### `AppDelegate.m`: ```objc // N/A ```


Android

Click To Expand

#### Have you converted to AndroidX? - [ ] my application is an AndroidX application? - [ ] I am using `android/gradle.settings` `jetifier=true` for Android compatibility? - [ ] I am using the NPM package `jetifier` for react-native compatibility? #### `android/build.gradle`: ```groovy // N/A ``` #### `android/app/build.gradle`: ```groovy // N/A ``` #### `android/settings.gradle`: ```groovy // N/A ``` #### `MainApplication.java`: ```java // N/A ``` #### `AndroidManifest.xml`: ```xml ```


Environment

Click To Expand

**`react-native info` output:** ``` System: OS: macOS 11.2.1 CPU: (8) x64 Apple M1 Memory: 23.78 MB / 8.00 GB Shell: 5.8 - /bin/zsh Binaries: Node: 14.15.4 - /usr/local/bin/node Yarn: 1.22.10 - ~/WebstormProjects/skye2/node_modules/.bin/yarn npm: 7.4.0 - /opt/homebrew/bin/npm Watchman: 4.9.0 - /opt/homebrew/bin/watchman Managers: CocoaPods: 1.10.1 - /usr/local/bin/pod SDKs: iOS SDK: Platforms: iOS 14.4, DriverKit 20.2, macOS 11.1, tvOS 14.3, watchOS 7.2 Android SDK: API Levels: 28, 30 Build Tools: 28.0.3, 30.0.3 System Images: android-30 | Google APIs Intel x86 Atom Android NDK: Not Found IDEs: Android Studio: 4.1.2 4.1.2 Xcode: 12.4/12D4e - /usr/bin/xcodebuild Languages: Java: 1.8.0_282 - /usr/bin/javac Python: 2.7.16 - /usr/bin/python npmPackages: @react-native-community/cli: Not Found react: 16.13.1 => 16.13.1 react-native: 0.63.4 => 0.63.4 react-native-macos: Not Found npmGlobalPackages: *react-native*: Not Found``` - **Platform that you're experiencing the issue on**: - [ ] iOS - [ ] Android - [x] **iOS** but have not tested behavior on Android - [ ] **Android** but have not tested behavior on iOS - [ ] Both - **`react-native-firebase` version you're using that has this issue:** - `` - **`Firebase` module(s) you're using that has the issue:** - `e.g. Instance ID` - **Are you using `TypeScript`?** - No - `Y/N` & `VERSION`

mikehardy commented 3 years ago

interesting - two quick notes

To be clear, neither of those have bearing on your problem - I just noticed them

I'm not aware of any problems in the library around this method so I strongly suspect an API usage error or project config error of some sort

Do you have an App.js that minimally reproduces the problem so we can test? Can you confirm this was on a real device?

Vadko commented 3 years ago

Thank you for your notes, indeed, you are right about those 2 problems that you've described :) Basically, I set up my new project using package.json from the old project so I didn't notice that Async Storage has moved from that. About the Podfile - as I remember, react native vector icons require to be linked in the Podfile, I'm not sure at all but I can remember that I faced some issues when was not doing that.

Yes, the problem appears on the real device, on the local emulator library opens Recaptcha window and everything works great.

Hmm, I think I can invite you to my repository so you can clone the project and have a look. What do you think about that?

Thank you for the quick answer!

mikehardy commented 3 years ago

I would prefer a clean / minimal reproduction of the problem in the form of an App.js that I can drop in a known-well-configured clean project :-)

Vadko commented 3 years ago

Okay then:

import auth from "@react-native-firebase/auth";
import React, { useState, useEffect } from "react";
import {
  Text,
  SafeAreaView,
  View,
  StyleSheet,
  Keyboard,
  Button,
} from "react-native";
import {
  CodeField,
  Cursor,
  useBlurOnFulfill,
  useClearByFocusCell,
} from "react-native-confirmation-code-field";

const ConfirmSms = () => {
  const [confirm, setConfirm] = useState();
  const [verificationCode, setVerificationCode] = useState("");

  const CELL_COUNT = 6;

  const ref = useBlurOnFulfill({
    value: confirm,
    cellCount: CELL_COUNT,
  });

  const [props, getCellOnLayoutHandler] = useClearByFocusCell({
    value: verificationCode,
    setValue: setVerificationCode,
  });

  useEffect(() => {
    sendMessage("+123456789");
  }, []);

  const sendCode = async () => {
    Keyboard.dismiss();
    try {
      await confirm.confirm(verificationCode);
    } catch (error) {
      console.error(error);
    }
  };

  const sendMessage = async (phone) => {
    try {
      const confirmation = await auth().signInWithPhoneNumber(phone);
      setConfirm(confirmation);
    } catch (error) {
      console.error(error);
    }
  };

  return (
    <View style={{ flex: 1, paddingBottom: 20 }}>
      <SafeAreaView style={styles.container}>
        <View style={styles.codeFieldWrapper}>
          <View style={styles.titleWrapper}>
            <Text style={styles.subtitle}>
              please enter the verification code
            </Text>
          </View>
          <CodeField
            ref={ref}
            {...props}
            value={verificationCode}
            onChangeText={setVerificationCode}
            cellCount={CELL_COUNT}
            rootStyle={styles.codeFieldRoot}
            keyboardType="number-pad"
            textContentType="oneTimeCode"
            renderCell={({ index, symbol, isFocused }) => (
              <View
                onLayout={getCellOnLayoutHandler(index)}
                key={index}
                style={[styles.cellRoot, isFocused && styles.focusCell]}
              >
                <Text style={styles.cellText}>
                  {symbol || (isFocused ? <Cursor /> : null)}
                </Text>
              </View>
            )}
          />
          <View style={{ marginTop: 50 }}>
            <Button onPress={sendCode} title="Confirm code" />
          </View>
        </View>
      </SafeAreaView>
    </View>
  );
};

export default ConfirmSms;

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: "center",
    justifyContent: "center",
  },
  codeFieldWrapper: {
    alignItems: "center",
    justifyContent: "center",
    flex: 1,
    marginBottom: 150,
  },
  titleWrapper: { alignItems: "center" },
  title: {
    marginBottom: 0,
  },
  subtitle: {
    fontSize: 23,
    fontWeight: "bold",
    color: "#6F778C",
    marginTop: 20,
    marginBottom: 40,
  },
  codeFieldRoot: {
    marginTop: 20,
    paddingHorizontal: 30,
    width: "100%",
  },
  cellRoot: {
    width: 50,
    height: 50,
    justifyContent: "center",
    alignItems: "center",
    borderBottomColor: "#6F778C",
    borderBottomWidth: 3,
  },
  cellText: {
    color: "#6F778C",
    fontSize: 32,
    textAlign: "center",
  },
  focusCell: {
    borderBottomColor: "#32C5FF",
    borderBottomWidth: 4,
  },
  button: {
    marginTop: "auto",
    width: 180,
  },
});

I removed some UI (I took a file from my working project) and tested it using an emulator - everything works fine.

mikehardy commented 3 years ago

"everything works fine" --> to be clear before I spend any time trying this, does that mean "react-native-firebase is working fine" or does that mean "the file executes correctly as intended and reproduces the problem"

Sorry to be possibly dense, but "everything works fine" could be interpreted as not able to reproduce

Vadko commented 3 years ago

I apologize for not specifying what I mean by "works fine" :)

So, I mean, it works with RECaptcha verification (through iOS emulator) and still reproduces problem with error invalid-app-credential on the real device.

oarsheo commented 3 years ago

Go to Frebase general settings Copy Encoded app ID and set to URL Schemes in Info.plist

mikehardy commented 3 years ago

I think @oarsheo is probably right, but in general the upstream ios firebase phone auth integration documentation will rule here - this will not be anything specific to react-native-firebase so I will close this. I will note that I actually do phone auth in my main work app so I know this works, I'm not just closing it to close it - it's project-specific and firebase-ios-sdk specific, where their docs should provide all the details

anhnch commented 1 year ago

Somehow, one day suddenly I got this error on iOS Simulator. I tried copy the Encoded app ID to URL Scheme and re-ran the debug mode, it didn't work. But after doing something I don't remember exactly, but nothing special except deleting the app on Simulator, cleaning and rebuilding the project, then It worked (on iPad Pro iOS 16)

I tried again on Simulator iphone 14 (iOS 16) and other simulators, it didn't work. So I went back to the iPad Pro iOS 16, logged out and logged in again. The error showed up again.

I downloaded iOS 15.5 simulator and tried again. It worked!

There may be many reasons that cause the [auth/invalid-app-credential] issue, but I guess iOS version 16 on Simulator is one of them.

And one note for anyone who also have this issue, make sure that the API key in Google cloud has no restriction, or it won't be able to fallback to reCaptcha.

yoavprat commented 1 year ago

Somehow, one day suddenly I got this error on iOS Simulator. I tried copy the Encoded app ID to URL Scheme and re-ran the debug mode, it didn't work. But after doing something I don't remember exactly, but nothing special except deleting the app on Simulator, cleaning and rebuilding the project, then It worked (on iPad Pro iOS 16)

I tried again on Simulator iphone 14 (iOS 16) and other simulators, it didn't work. So I went back to the iPad Pro iOS 16, logged out and logged in again. The error showed up again.

I downloaded iOS 15.5 simulator and tried again. It worked!

There may be many reasons that cause the [auth/invalid-app-credential] issue, but I guess iOS version 16 on Simulator is one of them.

And one note for anyone who also have this issue, make sure that the API key in Google cloud has no restriction, or it won't be able to fallback to reCaptcha.

I have the same issue. can confirm it works on iOS 15.* Simulators but not iOS 16. what do you mean with api key? can you explain?

skibaalex commented 1 year ago

@anhnch what do you mean by restrictions? where do I check if it is restricted, and if so how do I remove it?

is there a way to always use ReCaptcha?

yoavprat commented 1 year ago

Hi, please follow the Flutter fix it also worked for me on React Native https://stackoverflow.com/questions/74340881/invalid-app-credential-token-mismatch-in-flutter-firebase-auth

GabeConsalter commented 1 year ago

Hi, please follow the Flutter fix it also worked for me on React Native https://stackoverflow.com/questions/74340881/invalid-app-credential-token-mismatch-in-flutter-firebase-auth

Thank you for your answer @yoavapi. This Flutter fix has some native code differences from to React Native approach, can you show how you implemented the solution for your React Native project? This will be more clear to help me and others.

Thanks.

mikehardy commented 1 year ago

https://github.com/firebase/firebase-ios-sdk/commit/3d6305a9fa5295773ae447d82badd441a0a55f1b - that's the upstream commit that fixes this, it appears to be a local simulator issue on Ventura + iOS16 simulators? And the commit forces the recaptcha flow for now.

10.2.0 literally just released a few hours ago so I haven't released it here yet but I will shortly. Until then @GabeConsalter you might retry with a Podfile override to pull firebase-ios-sdk 10.2.0 in?

https://rnfirebase.io/#ios

GabeConsalter commented 1 year ago

firebase/firebase-ios-sdk@3d6305a - that's the upstream commit that fixes this, it appears to be a local simulator issue on Ventura + iOS16 simulators? And the commit forces the recaptcha flow for now.

10.2.0 literally just released a few hours ago so I haven't released it here yet but I will shortly. Until then @GabeConsalter you might retry with a Podfile override to pull firebase-ios-sdk 10.2.0 in?

https://rnfirebase.io/#ios

I tried overriding the sdk version but I'm having some other firebase modules version mismatch.

image

In this case, when I'm using some other firebase modules, how should I override the version?

mikehardy commented 1 year ago

Pasting images is very difficult for people on small devices trying to help you, please paste text in triple-backticks

I can't understand why your Podfile.lock would be bringing in version 8 of firebase-ios-sdk, that implies that you are (or were) still on version 14 of react-native-firebase? You are likely trying to avoid use_frameworks? Unfortunately, that's not viable. We are two major versions along here and we're not stopping, in order to access the new firebase-ios-sdk versions with the bugfix you apparently need, you'll need to upgrade to latest stable

GabeConsalter commented 1 year ago

Pasting images is very difficult for people on small devices trying to help you, please paste text in triple-backticks

I can't understand why your Podfile.lock would be bringing in version 8 of firebase-ios-sdk, that implies that you are (or were) still on version 14 of react-native-firebase? You are likely trying to avoid use_frameworks? Unfortunately, that's not viable. We are two major versions along here and we're not stopping, in order to access the new firebase-ios-sdk versions with the bugfix you apparently need, you'll need to upgrade to latest stable

I had some problems with use_frameworks because of other libs on my project with this requirement. But I fixed all my dependencies, forced the 10.2.0 with use_frameworks and now the auth is working.

Thank you @mikehardy.

mikehardy commented 1 year ago

Just in time for me to publish an update here with firebase-ios-sdk 10.2.0 bundled 😆 - but fantastic that you got use_frameworks working and you can get back up to date now, I know that can be very difficult.

anhnch commented 1 year ago

@anhnch what do you mean by restrictions? where do I check if it is restricted, and if so how do I remove it?

is there a way to always use ReCaptcha?

FYI, If you go to https://console.cloud.google.com/apis/credentials?project=yourproject you'll see iOS key (auto created by Firebase) or something like that. Click the key and check the Application restrictions, if you set it to iOS apps, then the recaptcha may get perrmission denied.

Anyway, Mike has published a new update

Chasty commented 1 year ago

FYI if u don't want to update all your deps,

changing your .entitlements will work.

from

<key>aps-environment</key>
<string>development</string>

to

<key>aps-environment</key>
<string>unknown</string>
rohanvasishth commented 1 year ago

firebase/firebase-ios-sdk@3d6305a - that's the upstream commit that fixes this, it appears to be a local simulator issue on Ventura + iOS16 simulators? And the commit forces the recaptcha flow for now.

10.2.0 literally just released a few hours ago so I haven't released it here yet but I will shortly. Until then @GabeConsalter you might retry with a Podfile override to pull firebase-ios-sdk 10.2.0 in?

https://rnfirebase.io/#ios

Hey Mike, I do think this is the issue and why it isn't working. However, I think there are some bugs upgrading to version 10.2.0 that I face. These are the specific errors:

[!] CocoaPods could not find compatible versions for pod "FBSDKCoreKit": In Podfile: ExpoAdapterFBSDKNext (from ../node_modules/react-native-fbsdk-next/ios) was resolved to 11.2.1, which depends on FBSDKCoreKit

react-native-fbsdk-next (from `../node_modules/react-native-fbsdk-next`) was resolved to 11.2.1, which depends on
  react-native-fbsdk-next/Share (= 11.2.1) was resolved to 11.2.1, which depends on
    FBSDKGamingServicesKit (~> 15.0.0) was resolved to 15.0.0, which depends on
      FBSDKCoreKit (= 15.0.0)

CocoaPods could not find compatible versions for pod "GTMSessionFetcher/Core": In Podfile: RNFBAuth (from ../node_modules/@react-native-firebase/auth) was resolved to 18.1.0, which depends on Firebase/Auth (= 10.11.0) was resolved to 10.11.0, which depends on FirebaseAuth (~> 10.11.0) was resolved to 10.11.0, which depends on GTMSessionFetcher/Core (< 4.0, >= 2.1)

RNGoogleSignin (from `../node_modules/@react-native-community/google-signin`) was resolved to 5.0.0, which depends on
  GoogleSignIn (~> 5.0.0) was resolved to 5.0.2, which depends on
    GTMSessionFetcher/Core (~> 1.1)

I came across this stack overflow post which encounters this issue and it recommends using version 9.6.0 of firebase to avoid the issue. Obviously, this would mean not being able to access the fix in 10.2.0. Here is the post: https://stackoverflow.com/questions/74304290/cocoapods-could-not-find-compatible-versions-for-pod-gtmsessionfetcher-core

Do you have any thoughts on this? (Btw the [auth/invalid-app-credential] is only an error for me on the simulator. on device it works fine.)

adriaanbalt commented 8 months ago

I was also experiencing this error. I found the following threads:

Stackoverflow: https://stackoverflow.com/a/75173784/5423545

This is what I did to fix this bug.

  1. I logged into Apple Developer website and went to Certs, Ids, Profiles > Keys https://developer.apple.com/account/resources/authkeys/list
  2. Then I created a new APN key.
  3. I downloaded the APN key and copied the "Key ID" (if you do not copy it now that is okay, yo can get it if you click on the Key you created in the list screen).
  4. Logged into firebase console https://console.firebase.google.com/
  5. Navigated to Project Settings > Cloud Messaging
  6. Scroll down to "Apple app configurations" and upload the APN key you created above and paste the key ID.
  7. I refreshed my app on my Device and was able to login. I didn't do anything more.
joaqo commented 7 months ago

I was also experiencing this error. I found the following threads:

Stackoverflow: https://stackoverflow.com/a/75173784/5423545

This is what I did to fix this bug.

  1. I logged into Apple Developer website and went to Certs, Ids, Profiles > Keys https://developer.apple.com/account/resources/authkeys/list
  2. Then I created a new APN key.
  3. I downloaded the APN key and copied the "Key ID" (if you do not copy it now that is okay, yo can get it if you click on the Key you created in the list screen).
  4. Logged into firebase console https://console.firebase.google.com/
  5. Navigated to Project Settings > Cloud Messaging
  6. Scroll down to "Apple app configurations" and upload the APN key you created above and paste the key ID.
  7. I refreshed my app on my Device and was able to login. I didn't do anything more.

Hi @adriaanbalt I followed your advice and was able to stop getting the error message mentioned in the issue's title, but now I am always getting prompted for a recaptcha, even while using a physical device. Did you experience this as well?

adriaanbalt commented 7 months ago

@joaqo didn't have the recaptcha issue you're mentioning. This approach isn't directly associated with the recaptcha implementation. For recaptcha I copied the react native firebase approach, restyled it, and it worked. Maybe your issue has something to do with async storage or saving the user's session. What does your code look like? Maybe I can help..

joaqo commented 7 months ago

Hi thanks @adriaanbalt! I ended up solving it by manually adding the Push notification and Background modes capability with Background fetch and Remote notifications options to my Xcode project.

Funnily enough I then reproduced this and didn't need to manually enable these features. So I am not entirely sure if it was actually necessary, and what actually fixed it on my first go around. Thanks for offering to help anyways!

myeljoud commented 6 months ago

@adriaanbalt, worked like a charm. Thanks!

unledrob commented 6 months ago

In my case I am using the non-swizzled approach and while in the past I could use FIRAuthAPNSTokenTypeUnknown, now I have to specify which in - (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken...

  #if DEBUG
    FIRAuthAPNSTokenType type = FIRAuthAPNSTokenTypeSandbox;
  #else
    FIRAuthAPNSTokenType type = FIRAuthAPNSTokenTypeProd;
  #endif

  [[FIRAuth auth] setAPNSToken:deviceToken type: type];

If you're not using the non-swizzled setup, don't worry about this.