firebase / flutterfire

🔥 A collection of Firebase plugins for Flutter apps.
https://firebase.google.com/docs/flutter/setup
BSD 3-Clause "New" or "Revised" License
8.66k stars 3.96k forks source link

🐛 [firebase_auth] [firebase_auth/invalid-credential] The supplied auth credential is malformed, has expired, or is not currently supported error after credential-already-in-use exception #11841

Closed ashu2902 closed 10 months ago

ashu2902 commented 11 months ago

Bug report

Describe the bug this is the exact description of the problem:

After the anonymous sign-in, when I try to link the credentials of the anonymous account to PhoneAuth credentials. If the PhoneAuth credential is an already existing account, it throws an exception "credential-already-in-use". in the catch block, I delete the anonymous account and use the signInWithCredentials(), which I receive in the catch block. (since the error is thrown by 'linkWithCredential()', I receive the credentials along with the token). At the third step it started throwing an error: [firebase_auth/invalid-credential] The supplied auth credential is malformed, has expired, or is not currently supported. Also, this is happening only on my iOS devices and it is working perfectly on Android.

Steps to reproduce

Steps to reproduce the behavior:

1.Sign in the user with anonymous provider

  1. Try to link the credentials with phone number of an account that already exists in the firebase authentication
  2. in the catch block of linkWithCredentials, attempt signInWithCredentials and use the credentials provided in the error.credentials
  3. it throws the error: [firebase_auth/invalid-credential] The supplied auth credential is malformed, has expired, or is not currently supported.

Expected behavior

The expected behavior is that the user would be logged in with the credentials received in the catch block.

Sample project


Additional context

Add any other context about the problem here.


Flutter doctor

Run flutter doctor and paste the output below:

Click To Expand ``` [√] Flutter (Channel stable, 3.13.7, on Microsoft Windows [Version 10.0.22621.2428], locale en-IN) [√] Windows Version (Installed version of Windows is version 10 or higher) [√] Android toolchain - develop for Android devices (Android SDK version 31.0.0) [√] Chrome - develop for the web [√] Visual Studio - develop Windows apps (Visual Studio Build Tools 2019 16.11.18) [!] Android Studio (not installed) [√] VS Code (version 1.84.0) [√] Connected device (4 available) [√] Network resources ! Doctor found issues in 1 category. ```

Flutter dependencies

Run flutter pub deps -- --style=compact and paste the output below:

Click To Expand ``` Dart SDK 3.1.3 Flutter SDK 3.13.7 seek_app 1.21.39 dependencies: - algolia_helper_flutter 0.5.0 [algolia_insights algoliasearch collection flutter logging meta rxdart] - algolia_insights 0.2.2 [algolia_client_insights collection flutter hive logging meta path_provider rxdart uuid] - auto_size_text 3.0.0 [flutter] - cached_network_image 3.3.0 [cached_network_image_platform_interface cached_network_image_web flutter flutter_cache_manager octo_image] - carousel_slider 4.2.1 [flutter] - cloud_firestore 4.12.2 [cloud_firestore_platform_interface cloud_firestore_web collection firebase_core firebase_core_platform_interface flutter meta] - cloud_functions 4.5.3 [cloud_functions_platform_interface cloud_functions_web firebase_core firebase_core_platform_interface flutter] - cupertino_icons 1.0.6 - expandable 5.0.1 [flutter] - firebase_analytics 10.6.3 [firebase_analytics_platform_interface firebase_analytics_web firebase_core firebase_core_platform_interface flutter] - firebase_auth 4.12.1 [firebase_auth_platform_interface firebase_auth_web firebase_core firebase_core_platform_interface flutter meta] - firebase_core 2.21.0 [firebase_core_platform_interface firebase_core_web flutter meta] - firebase_crashlytics 3.4.3 [firebase_core firebase_core_platform_interface firebase_crashlytics_platform_interface flutter stack_trace] - firebase_in_app_messaging 0.7.4+3 [firebase_core firebase_core_platform_interface firebase_in_app_messaging_platform_interface flutter meta] - firebase_messaging 14.7.3 [firebase_core firebase_core_platform_interface firebase_messaging_platform_interface firebase_messaging_web flutter meta] - firebase_performance 0.9.3+3 [firebase_core firebase_core_platform_interface firebase_performance_platform_interface firebase_performance_web flutter] - firebase_remote_config 4.3.3 [firebase_core firebase_core_platform_interface firebase_remote_config_platform_interface firebase_remote_config_web flutter] - firebase_storage 11.4.1 [firebase_core firebase_core_platform_interface firebase_storage_platform_interface firebase_storage_web flutter] - fl_country_code_picker 0.1.6+1 [flutter flutter_localizations scrollable_positioned_list] - flutter 0.0.0 [characters collection material_color_utilities meta vector_math web sky_engine] - flutter_branch_sdk 6.9.0 [flutter flutter_web_plugins plugin_platform_interface js] - flutter_cache_manager 3.3.1 [clock collection file flutter http path path_provider rxdart sqflite uuid] - flutter_local_notifications 13.0.0 [clock flutter flutter_local_notifications_linux flutter_local_notifications_platform_interface timezone] - flutter_markdown 0.6.18 [flutter markdown meta path] - flutter_screenutil 5.9.0 [flutter] - flutter_svg 2.0.9 [flutter vector_graphics vector_graphics_codec vector_graphics_compiler] - fluttertoast 8.2.2 [flutter flutter_web_plugins] - get 4.6.6 [flutter] - get_storage 2.1.1 [flutter get path_provider] - google_fonts 6.1.0 [flutter http path_provider crypto] - group_radio_button 1.3.0 [flutter] - image_cropper 5.0.0 [flutter image_cropper_platform_interface image_cropper_for_web] - image_picker 1.0.4 [flutter image_picker_android image_picker_for_web image_picker_ios image_picker_linux image_picker_macos image_picker_platform_interface image_picker_windows] - infinite_scroll_pagination 4.0.0 [flutter flutter_staggered_grid_view sliver_tools] - lottie 2.7.0 [archive flutter path vector_math] - package_info_plus 4.2.0 [ffi flutter flutter_web_plugins http meta path package_info_plus_platform_interface win32] - palette_generator 0.3.3+3 [collection flutter] - percent_indicator 4.2.3 [flutter] - permission_handler 11.0.1 [flutter meta permission_handler_android permission_handler_apple permission_handler_windows permission_handler_platform_interface] - platform 3.1.3 - share_plus 7.2.1 [cross_file meta mime flutter flutter_web_plugins share_plus_platform_interface file url_launcher_web url_launcher_windows url_launcher_linux url_launcher_platform_interface ffi win32] - shimmer 3.0.0 [flutter] - smooth_page_indicator 1.1.0 [flutter] - sms_autofill 2.3.0 [pin_input_text_field flutter] - tap_debouncer 2.2.0 [flutter] - url_launcher 6.2.1 [flutter url_launcher_android url_launcher_ios url_launcher_linux url_launcher_macos url_launcher_platform_interface url_launcher_web url_launcher_windows] - webview_flutter 4.4.2 [flutter webview_flutter_android webview_flutter_platform_interface webview_flutter_wkwebview] dev dependencies: - flutter_lints 3.0.1 [lints] - flutter_test 0.0.0 [flutter test_api matcher path fake_async clock stack_trace vector_math async boolean_selector characters collection material_color_utilities meta source_span stream_channel string_scanner term_glyph web] transitive dependencies: - _flutterfire_internals 1.3.11 [collection firebase_core firebase_core_platform_interface flutter meta] - algolia_client_core 0.3.0 [dio] - algolia_client_insights 0.3.0 [algolia_client_core json_annotation collection] - algolia_client_search 0.3.0 [algolia_client_core json_annotation collection] - algoliasearch 0.3.0 [algolia_client_core algolia_client_search algolia_client_insights json_annotation collection] - archive 3.4.8 [crypto path pointycastle] - args 2.4.2 - async 2.11.0 [collection meta] - boolean_selector 2.1.1 [source_span string_scanner] - cached_network_image_platform_interface 3.0.0 [flutter flutter_cache_manager] - cached_network_image_web 1.1.0 [cached_network_image_platform_interface flutter flutter_cache_manager] - characters 1.3.0 - clock 1.1.1 - cloud_firestore_platform_interface 6.0.3 [_flutterfire_internals collection firebase_core flutter meta plugin_platform_interface] - cloud_firestore_web 3.8.3 [_flutterfire_internals cloud_firestore_platform_interface collection firebase_core firebase_core_web flutter flutter_web_plugins js] - cloud_functions_platform_interface 5.5.6 [firebase_core flutter meta plugin_platform_interface] - cloud_functions_web 4.6.6 [cloud_functions_platform_interface firebase_core firebase_core_web flutter flutter_web_plugins js] - collection 1.17.2 - convert 3.1.1 [typed_data] - cross_file 0.3.3+6 [js meta] - crypto 3.0.3 [typed_data] - dbus 0.7.8 [args ffi meta xml] - dio 5.3.3 [async http_parser meta path] - fake_async 1.3.1 [clock collection] - ffi 2.1.0 - file 6.1.4 [meta path] - file_selector_linux 0.9.2+1 [cross_file file_selector_platform_interface flutter] - file_selector_macos 0.9.3+3 [cross_file file_selector_platform_interface flutter] - file_selector_platform_interface 2.6.1 [cross_file flutter http plugin_platform_interface] - file_selector_windows 0.9.3+1 [cross_file file_selector_platform_interface flutter] - firebase_analytics_platform_interface 3.7.5 [_flutterfire_internals firebase_core flutter meta plugin_platform_interface] - firebase_analytics_web 0.5.5+5 [_flutterfire_internals firebase_analytics_platform_interface firebase_core firebase_core_web flutter flutter_web_plugins js] - firebase_auth_platform_interface 7.0.3 [_flutterfire_internals collection firebase_core flutter meta plugin_platform_interface] - firebase_auth_web 5.8.6 [firebase_auth_platform_interface firebase_core firebase_core_web flutter flutter_web_plugins http_parser js meta] - firebase_core_platform_interface 5.0.0 [collection flutter flutter_test meta plugin_platform_interface] - firebase_core_web 2.8.1 [firebase_core_platform_interface flutter flutter_web_plugins js meta] - firebase_crashlytics_platform_interface 3.6.11 [_flutterfire_internals collection firebase_core flutter meta plugin_platform_interface] - firebase_in_app_messaging_platform_interface 0.2.4+11 [_flutterfire_internals firebase_core flutter meta plugin_platform_interface] - firebase_messaging_platform_interface 4.5.12 [_flutterfire_internals firebase_core flutter meta plugin_platform_interface] - firebase_messaging_web 3.5.12 [_flutterfire_internals firebase_core firebase_core_web firebase_messaging_platform_interface flutter flutter_web_plugins js meta] - firebase_performance_platform_interface 0.1.4+11 [_flutterfire_internals firebase_core flutter plugin_platform_interface] - firebase_performance_web 0.1.4+11 [_flutterfire_internals firebase_core firebase_core_web firebase_performance_platform_interface flutter flutter_web_plugins js] - firebase_remote_config_platform_interface 1.4.11 [_flutterfire_internals firebase_core flutter meta plugin_platform_interface] - firebase_remote_config_web 1.4.11 [firebase_core firebase_core_web firebase_remote_config_platform_interface flutter flutter_web_plugins js] - firebase_storage_platform_interface 5.0.1 [_flutterfire_internals collection firebase_core flutter meta plugin_platform_interface] - firebase_storage_web 3.6.12 [_flutterfire_internals async firebase_core firebase_core_web firebase_storage_platform_interface flutter flutter_web_plugins http js meta] - flutter_local_notifications_linux 3.0.0+1 [dbus ffi flutter flutter_local_notifications_platform_interface path xdg_directories] - flutter_local_notifications_platform_interface 6.0.0 [flutter plugin_platform_interface] - flutter_localizations 0.0.0 [flutter intl characters clock collection material_color_utilities meta path vector_math web] - flutter_plugin_android_lifecycle 2.0.17 [flutter] - flutter_staggered_grid_view 0.7.0 [flutter] - flutter_web_plugins 0.0.0 [flutter characters collection material_color_utilities meta vector_math web] - hive 2.2.3 [meta crypto] - http 1.1.0 [async http_parser meta] - http_parser 4.0.2 [collection source_span string_scanner typed_data] - image_cropper_for_web 3.0.0 [flutter flutter_web_plugins image_cropper_platform_interface js] - image_cropper_platform_interface 5.0.0 [flutter plugin_platform_interface http] - image_picker_android 0.8.8+2 [flutter flutter_plugin_android_lifecycle image_picker_platform_interface] - image_picker_for_web 3.0.1 [flutter flutter_web_plugins image_picker_platform_interface mime] - image_picker_ios 0.8.8+4 [flutter image_picker_platform_interface] - image_picker_linux 0.2.1+1 [file_selector_linux file_selector_platform_interface flutter image_picker_platform_interface] - image_picker_macos 0.2.1+1 [file_selector_macos file_selector_platform_interface flutter image_picker_platform_interface] - image_picker_platform_interface 2.9.1 [cross_file flutter http plugin_platform_interface] - image_picker_windows 0.2.1+1 [file_selector_platform_interface file_selector_windows flutter image_picker_platform_interface] - intl 0.18.1 [clock meta path] - js 0.6.7 [meta] - json_annotation 4.8.1 [meta] - lints 3.0.0 - logging 1.2.0 - markdown 7.1.1 [args meta] - matcher 0.12.16 [async meta stack_trace term_glyph test_api] - material_color_utilities 0.5.0 [collection] - meta 1.9.1 - mime 1.0.4 - octo_image 2.0.0 [flutter] - package_info_plus_platform_interface 2.0.1 [flutter meta plugin_platform_interface] - path 1.8.3 - path_parsing 1.0.1 [vector_math meta] - path_provider 2.1.1 [flutter path_provider_android path_provider_foundation path_provider_linux path_provider_platform_interface path_provider_windows] - path_provider_android 2.2.1 [flutter path_provider_platform_interface] - path_provider_foundation 2.3.1 [flutter path_provider_platform_interface] - path_provider_linux 2.2.1 [ffi flutter path path_provider_platform_interface xdg_directories] - path_provider_platform_interface 2.1.1 [flutter platform plugin_platform_interface] - path_provider_windows 2.2.1 [ffi flutter path path_provider_platform_interface win32] - permission_handler_android 11.1.0 [flutter permission_handler_platform_interface] - permission_handler_apple 9.1.4 [flutter permission_handler_platform_interface] - permission_handler_platform_interface 3.12.0 [flutter meta plugin_platform_interface] - permission_handler_windows 0.1.3 [flutter permission_handler_platform_interface] - petitparser 5.4.0 [meta] - pin_input_text_field 4.5.1 [flutter] - plugin_platform_interface 2.1.6 [meta] - pointycastle 3.7.3 [collection convert js] - process 4.2.4 [file path platform] - rxdart 0.27.7 - scrollable_positioned_list 0.3.8 [flutter collection] - share_plus_platform_interface 3.3.1 [cross_file flutter meta mime plugin_platform_interface path_provider uuid] - sky_engine 0.0.99 - sliver_tools 0.2.12 [flutter] - source_span 1.10.0 [collection path term_glyph] - sprintf 7.0.0 - sqflite 2.3.0 [flutter sqflite_common path] - sqflite_common 2.5.0+1 [synchronized path meta] - stack_trace 1.11.0 [path] - stream_channel 2.1.1 [async] - string_scanner 1.2.0 [source_span] - synchronized 3.1.0 - term_glyph 1.2.1 - test_api 0.6.0 [async boolean_selector collection meta source_span stack_trace stream_channel string_scanner term_glyph] - timezone 0.9.2 [path] - typed_data 1.3.2 [collection] - url_launcher_android 6.2.0 [flutter url_launcher_platform_interface] - url_launcher_ios 6.2.0 [flutter url_launcher_platform_interface] - url_launcher_linux 3.1.0 [flutter url_launcher_platform_interface] - url_launcher_macos 3.1.0 [flutter url_launcher_platform_interface] - url_launcher_platform_interface 2.2.0 [flutter plugin_platform_interface] - url_launcher_web 2.2.0 [flutter flutter_web_plugins url_launcher_platform_interface] - url_launcher_windows 3.1.0 [flutter url_launcher_platform_interface] - uuid 4.1.0 [crypto sprintf] - vector_graphics 1.1.9+1 [flutter vector_graphics_codec] - vector_graphics_codec 1.1.9+1 - vector_graphics_compiler 1.1.9+1 [args meta path_parsing xml vector_graphics_codec path] - vector_math 2.1.4 - web 0.1.4-beta - webview_flutter_android 3.12.1 [flutter webview_flutter_platform_interface] - webview_flutter_platform_interface 2.6.0 [flutter meta plugin_platform_interface] - webview_flutter_wkwebview 3.9.3 [flutter path webview_flutter_platform_interface] - win32 5.0.9 [ffi] - xdg_directories 0.2.0+3 [meta path process] - xml 6.3.0 [collection meta petitparser] ```

ashu2902 commented 11 months ago

@nohe427 Could you please take a look at this?

danagbemava-nc commented 11 months ago

Hi @ashu2902, please provide a complete minimal reproducible code sample in a repo that we can clone so that we can investigate this issue.

Thank you

MirceaX2Mobile commented 11 months ago

I can confirm this. I'm facing the same issue.

danagbemava-nc commented 11 months ago

Hi @MirceaX2Mobile, please provide a complete minimal reproducible code sample in a repo that we can clone so that we can investigate this issue.

Thank you

MirceaX2Mobile commented 10 months ago

Hello @danagbemava-nc @ashu2902 @russellwheatley @darshankawar! So I made a reproducible code. But you will need a Firebase Project with PhoneNumber Auth enabled. I will attach the code bellow. There are 2 textfields one for the phoneNumber, one for the otpCode, each textfield has a button for sendingSMS and sendingOTP.

After that you get credential-already-in-use error and then you use the credential from the error to log into the existing account.

logInToExistingAccount will throw The supplied auth credential is malformed, has expired or is not currently supported

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();

  if (FirebaseAuth.instance.currentUser == null) {
    await FirebaseAuth.instance.signInAnonymously();
  }

  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  TextEditingController _phoneNumberController = TextEditingController();
  TextEditingController _otpController = TextEditingController();
  final FirebaseAuth auth = FirebaseAuth.instance;
  String? _verificationId;
  String? _code;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('OTP Screen'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Padding(
              padding: const EdgeInsets.all(8.0),
              child: TextField(
                controller: _phoneNumberController,
                keyboardType: TextInputType.number,
                decoration: InputDecoration(
                  labelText: 'Enter Phone Number',
                ),
              ),
            ),
            Padding(
              padding: const EdgeInsets.all(8.0),
              child: ElevatedButton(
                onPressed: () {
                  String phoneNumber = _phoneNumberController.text;
                  print('Entered number: $phoneNumber');
                  verifyPhoneNumber();
                },
                child: Text('Send SMS'),
              ),
            ),
            Padding(
              padding: const EdgeInsets.all(8.0),
              child: TextField(
                controller: _otpController,
                keyboardType: TextInputType.number,
                decoration: InputDecoration(
                  labelText: 'Enter OTP',
                ),
              ),
            ),
            Padding(
              padding: const EdgeInsets.all(8.0),
              child: ElevatedButton(
                onPressed: () {
                  _code = _otpController.text;
                  print('Entered OTP: $_code');
                  verifyCode();
                },
                child: Text('Verify OTP'),
              ),
            ),
          ],
        ),
      ),
    );
  }

  @override
  void dispose() {
    _phoneNumberController.dispose();
    _otpController.dispose();
    super.dispose();
  }

  verifyPhoneNumber() async {
    await auth.verifyPhoneNumber(
      phoneNumber: _phoneNumberController.text,
      verificationCompleted: (PhoneAuthCredential credential) {
        linkAccountTo(credential);
      },
      verificationFailed: (FirebaseAuthException e) {
        print(e);
      },
      codeSent: (String verificationId, int? resendToken) {
        print(verificationId);
        _verificationId = verificationId;
      },
      codeAutoRetrievalTimeout: (String verificationId) {},
    );
  }

  verifyCode() {
    final verificationId = _verificationId;
    final code = _code;
    if (verificationId == null) {
      return;
    }
    if (code == null) {
      return;
    }

    linkAccountTo(createCredential(verificationId, code));
  }

  PhoneAuthCredential createCredential(String verificationId, String smsCode) {
    PhoneAuthCredential credential = PhoneAuthProvider.credential(
        verificationId: verificationId,
        smsCode: smsCode);
    return credential;
  }

  linkAccountTo(PhoneAuthCredential credential) async {
    try {
      await auth.currentUser?.linkWithCredential(credential);
    } on FirebaseAuthException catch (e) {
      switch (e.code) {
        case "provider-already-linked":
          final credential = e.credential;
          if (credential != null) {
            logInToExistingAccount(credential);
          }
          break;
        case "credential-already-in-use":
          final credential = e.credential;
          if (credential != null) {
            logInToExistingAccount(credential);
          }
          break;
        default:
          print(e.code);
      }
    }
  }

  logInToExistingAccount(AuthCredential credential) async {
    try {
      await auth.signInWithCredential(credential);

      final currentUser = auth.currentUser;
      if (currentUser == null) {
        return;
      }
    } on FirebaseAuthException catch (e) {
      print(e);
      // Here you get the error
      // The supplied auth credential is malformed, has expired or is not currently supported.
    }
  }
}

pubspec.yaml

  firebase_core: ^2.13.1
  firebase_in_app_messaging: ^0.7.3+2
  firebase_messaging: ^14.6.2
  firebase_analytics: ^10.4.2
  firebase_database: ^10.2.2
  firebase_auth: ^4.13.0
  firebase_crashlytics: ^3.3.2
  firebase_remote_config: ^4.2.2
danagbemava-nc commented 10 months ago

Thanks @MirceaX2Mobile, for the repro.

I can reproduce the issue.

Triage report.

These are the steps I used to reproduce the issue.

  1. Use the code sample from https://github.com/firebase/flutterfire/issues/11841#issuecomment-1806810498
  2. The app will sign in anonymously.
  3. Link the account to a phone number
  4. Logout and restart the app
  5. The app will sign in into a new account
  6. Try to link using the old number that was used in step 3

You will now get the exception [firebase_auth/invalid-credential] The supplied auth credential is malformed, has expired or is not currently supported.

There's another case of this in https://github.com/firebase/flutterfire/issues/11877, although it uses a different sign in method

cc @russellwheatley

MirceaX2Mobile commented 10 months ago

@danagbemava-nc No problem, glad to help you guys!