Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[firebase_auth]: getIdToken(false) doesn't refresh the token when it's expired or returns a null token #16771

Open
1 task done
Tom3652 opened this issue Nov 25, 2024 · 11 comments
Labels
Needs Attention This issue needs maintainer attention. platform: android Issues / PRs which are specifically for Android. platform: ios Issues / PRs which are specifically for iOS. plugin: auth resolution: needs-repro This issue could not be reproduced or needs an up to date reproduction on latest FlutterFire plugin. type: bug Something isn't working

Comments

@Tom3652
Copy link

Tom3652 commented Nov 25, 2024

Is there an existing issue for this?

  • I have searched the existing issues.

Which plugins are affected?

Auth

Which platforms are affected?

Android, iOS

Description

I am not sure this is an issue with the SDK or my misunderstanding of how it works, but i have a live app with few thousands of active users.
I have daily 2 recurring error from my Cloud Monitoring Dashboard from my Cloud functions, where i use the firebase_admin sdk in python.

  1. The first error is : ERROR:root:check_token : Illegal ID token provided: b''. ID token must be a non-empty string.
  2. The second error is : ERROR:root:check_token : Token expired, 1732476868 < 1732476998

The dart code called before each of my Cloud Function request is :

  Future<String> getIdToken({bool forceRefresh = false}) async {
    String idToken = "";
    try {
      if (_currentUser != null) {
        idToken = await FirebaseAuth.instance.currentUser!.getIdToken(forceRefresh) ?? "";
      }
    } catch (error) {
      print("Could not get id token of user $error");
      // This records a Crashlytics error non fatal
      AnalyticsAPI.logError(error, reason: "Could not get id token of current user");
    }
   return idToken;
  }

And i put the idToken in the headers of the HTTP request (i have public endpoints), not using the cloud_function package of firebase for Flutter.

The python code that throws the error is simply :

def check_token(token):
    try:
        decoded_token = auth.verify_id_token(token)
        logging.info(f"verified token : {decoded_token}")
        if "uid" in decoded_token:
            return decoded_token["uid"]
        return ""
    except Exception as e:
        logging.error(f"check_token : {e}")
        return ""

Now, this means either getIdToken(false) gives an outdated token, or a null one and my dart code returns an empty string instead.
In my Crashlytics dashboard i have no trace of any error coming from the AnalyticsAPI.logError(error, reason: "Could not get id token of current user"); so i am guessing the getIdToken() method is handling errors itself and returns Null in that case.

The documentation states :

/// Returns the current token if it has not expired. Otherwise, this will
/// refresh the token and return a new one.
///
/// If [forceRefresh] is true, the token returned will be refreshed regardless
/// of token expiration.

Questions / bugs :

Returns the current token if it has not expired. Otherwise, this will refresh the token and return a new one.

  1. From this statement and the logs i am receiving, is there a real potential issue ?

-> I have checked around on internet / SO / ChatGPT and the clock's phone could lead to this problem, so i have started to believe that when the app is backgrounded for a long time without causing an app restart, is it possible it may delay the local checks for the clock and get "non-expired" token for the local auth but that is actually expired ?

-> As a workaround, i have tried to use the second part of the documentation :

If [forceRefresh] is true, the token returned will be refreshed regardless of token expiration.

And i am calling getIdToken(forceRefresh: true) instead of false on the AppLifeCycleState.resumed case to refresh the tokens more often. This actually didn't change anything...

Note : i am guessing that calling getIdToken(forceRefresh: true) for each requests will increase the network response time as it consumes an extra call to Firebase auth backend right ?

-> If the expiration is not a bug, how to deal with that ?

  1. If the String is empty, that means the getIdToken(false) returns Null with my code, it happens actually very often but i don't know the reason, and it's not obvious to guess what is going on here unfortunately :/

Reproducing the issue

This is actually very hard to reproduce since i have never encounter this error myself when i debug or even when i use my own app live version... And especially if this is not a real bug but rather a behavior that i don't fully understand.

Firebase Core version

3.8.0

Flutter Version

3.24.5

Relevant Log Output

No response

Flutter dependencies

Expand Flutter dependencies snippet
Dart SDK 3.5.4
Flutter SDK 3.24.5
app_name 1.7.1+1

dependencies:
- animated_text_kit 4.2.2 [flutter characters]
- app_links 6.3.2 [flutter app_links_linux app_links_platform_interface app_links_web]
- app_settings 5.1.1 [flutter plugin_platform_interface]
- app_tracking_transparency 2.0.6 [flutter]
- audio_waveforms 1.1.1 [flutter]
- auto_size_text 3.0.0 [flutter]
- cached_network_image 3.4.1 [cached_network_image_platform_interface cached_network_image_web flutter flutter_cache_manager octo_image]
- circle_list 1.0.5 [flutter]
- connectivity_plus 6.1.0 [flutter flutter_web_plugins connectivity_plus_platform_interface web meta nm collection]
- country_picker 2.0.27 [collection universal_io flutter]
- cupertino_back_gesture 0.1.0 [flutter]
- cupertino_icons 1.0.8
- emoji_picker_flutter 3.1.0 [flutter flutter_web_plugins plugin_platform_interface shared_preferences web]
- extended_image 9.0.7 [extended_image_library flutter meta vector_math]
- firebase_analytics 11.3.5 [firebase_analytics_platform_interface firebase_analytics_web firebase_core firebase_core_platform_interface flutter]
- firebase_app_check 0.3.1+6 [firebase_app_check_platform_interface firebase_app_check_web firebase_core firebase_core_platform_interface flutter]
- firebase_auth 5.3.3 [firebase_auth_platform_interface firebase_auth_web firebase_core firebase_core_platform_interface flutter meta]
- firebase_core 3.8.0 [firebase_core_platform_interface firebase_core_web flutter meta]
- firebase_crashlytics 4.1.5 [firebase_core firebase_core_platform_interface firebase_crashlytics_platform_interface flutter stack_trace]
- firebase_database 11.1.6 [firebase_core firebase_core_platform_interface firebase_database_platform_interface firebase_database_web flutter]
- firebase_in_app_messaging 0.8.0+10 [firebase_core firebase_core_platform_interface firebase_in_app_messaging_platform_interface flutter meta]
- firebase_messaging 15.1.5 [firebase_core firebase_core_platform_interface firebase_messaging_platform_interface firebase_messaging_web flutter meta]
- firebase_performance 0.10.0+10 [firebase_core firebase_core_platform_interface firebase_performance_platform_interface firebase_performance_web flutter]
- firebase_remote_config 5.1.5 [firebase_core firebase_core_platform_interface firebase_remote_config_platform_interface firebase_remote_config_web flutter]
- firebase_storage 12.3.6 [firebase_core firebase_core_platform_interface firebase_storage_platform_interface firebase_storage_web flutter]
- fl_chart 0.68.0 [equatable flutter]
- flutter 0.0.0 [characters collection material_color_utilities meta vector_math sky_engine]
- flutter_app_badger 1.3.0 [flutter]
- flutter_email_sender 6.0.3 [flutter]
- flutter_linkify 6.0.0 [flutter linkify]
- flutter_localizations 0.0.0 [flutter intl characters clock collection material_color_utilities meta path vector_math]
- flutter_secure_storage 9.2.2 [flutter flutter_secure_storage_linux flutter_secure_storage_macos flutter_secure_storage_platform_interface flutter_secure_storage_web flutter_secure_storage_windows meta]
- flutter_signin_button 2.0.0 [flutter font_awesome_flutter]
- flutter_svg 2.0.15 [flutter http vector_graphics vector_graphics_codec vector_graphics_compiler]
- fluttertoast 8.2.8 [flutter flutter_web_plugins web]
- gallery_saver 2.3.3 [flutter path_provider http path]
- google_fonts 6.2.1 [flutter http path_provider crypto]
- google_mobile_ads 5.2.0 [meta flutter webview_flutter_android webview_flutter_wkwebview webview_flutter]
- http 1.2.2 [async http_parser meta web]
- image_editor 1.6.0 [flutter image_editor_platform_interface image_editor_common image_editor_ohos]
- image_picker 1.1.2 [flutter image_picker_android image_picker_for_web image_picker_ios image_picker_linux image_picker_macos image_picker_platform_interface image_picker_windows]
- in_app_review 2.0.10 [flutter in_app_review_platform_interface]
- login 0.0.1 [flutter firebase_core firebase_auth firebase_app_check connectivity_plus google_sign_in]
- lottie 3.1.3 [archive flutter http path vector_math]
- mention_tag_text_field 0.0.7 [collection flutter]
- mime 2.0.0
- package_info_plus 8.1.1 [ffi flutter flutter_web_plugins http meta path package_info_plus_platform_interface web win32 clock]
- path_provider 2.1.5 [flutter path_provider_android path_provider_foundation path_provider_linux path_provider_platform_interface path_provider_windows]
- permission_handler 11.3.1 [flutter meta permission_handler_android permission_handler_apple permission_handler_html permission_handler_windows permission_handler_platform_interface]
- provider 6.1.2 [collection flutter nested]
- pull_to_refresh_flutter3 2.0.2 [flutter]
- qr_flutter 4.1.0 [flutter qr]
- rive 0.13.18 [collection flutter flutter_web_plugins http meta plugin_platform_interface rive_common]
- screenshot 3.0.0 [flutter]
- scrollable_positioned_list 0.3.8 [flutter collection]
- share_plus 10.1.2 [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 web win32]
- shared_preferences 2.3.3 [flutter shared_preferences_android shared_preferences_foundation shared_preferences_linux shared_preferences_platform_interface shared_preferences_web shared_preferences_windows]
- translator 1.0.3+1 [http]
- uploader 0.0.1 [flutter firebase_core firebase_storage flutter_image_compress uuid video_thumbnail video_compress]
- url_launcher 6.3.1 [flutter url_launcher_android url_launcher_ios url_launcher_linux url_launcher_macos url_launcher_platform_interface url_launcher_web url_launcher_windows]
- uuid 4.5.1 [crypto sprintf meta fixnum]
- video_player 2.9.2 [flutter html video_player_android video_player_avfoundation video_player_platform_interface video_player_web]
- visibility_detector 0.4.0+2 [flutter]

dev dependencies:
- flutter_launcher_icons 0.14.1 [args checked_yaml cli_util image json_annotation path yaml]
- flutter_lints 5.0.0 [lints]
- flutter_native_splash 2.4.3 [args flutter flutter_web_plugins html image meta path universal_io xml yaml ansicolor]
- flutter_test 0.0.0 [flutter test_api matcher path fake_async clock stack_trace vector_math leak_tracker_flutter_testing async boolean_selector characters collection leak_tracker leak_tracker_testing material_color_utilities meta source_span stream_channel string_scanner term_glyph vm_service]

transitive dependencies:
- _flutterfire_internals 1.3.46 [collection firebase_core firebase_core_platform_interface flutter meta]
- ansicolor 2.0.3
- app_links_linux 1.0.3 [flutter app_links_platform_interface gtk]
- app_links_platform_interface 2.0.2 [flutter plugin_platform_interface]
- app_links_web 1.0.4 [flutter flutter_web_plugins app_links_platform_interface web]
- archive 3.6.1 [crypto path]
- args 2.6.0
- async 2.11.0 [collection meta]
- boolean_selector 2.1.1 [source_span string_scanner]
- cached_network_image_platform_interface 4.1.1 [flutter flutter_cache_manager]
- cached_network_image_web 1.3.1 [cached_network_image_platform_interface flutter flutter_cache_manager web]
- characters 1.3.0
- checked_yaml 2.0.3 [json_annotation source_span yaml]
- cli_util 0.4.2 [meta path]
- clock 1.1.1
- collection 1.18.0
- connectivity_plus_platform_interface 2.0.1 [flutter meta plugin_platform_interface]
- cross_file 0.3.4+2 [meta web]
- crypto 3.0.6 [typed_data]
- csslib 1.0.2 [source_span]
- dbus 0.7.10 [args ffi meta xml]
- equatable 2.0.7 [collection meta]
- extended_image_library 4.0.5 [crypto flutter http_client_helper js path path_provider web]
- fake_async 1.3.1 [clock collection]
- ffi 2.1.3
- file 7.0.1 [meta path]
- file_selector_linux 0.9.3+1 [cross_file file_selector_platform_interface flutter]
- file_selector_macos 0.9.4+2 [cross_file file_selector_platform_interface flutter]
- file_selector_platform_interface 2.6.2 [cross_file flutter http plugin_platform_interface]
- file_selector_windows 0.9.3+3 [cross_file file_selector_platform_interface flutter]
- firebase_analytics_platform_interface 4.2.7 [_flutterfire_internals firebase_core flutter meta plugin_platform_interface]
- firebase_analytics_web 0.5.10+4 [_flutterfire_internals firebase_analytics_platform_interface firebase_core firebase_core_web flutter flutter_web_plugins]
- firebase_app_check_platform_interface 0.1.0+40 [_flutterfire_internals firebase_core flutter meta plugin_platform_interface]
- firebase_app_check_web 0.2.0+2 [_flutterfire_internals firebase_app_check_platform_interface firebase_core firebase_core_web flutter flutter_web_plugins web]
- firebase_auth_platform_interface 7.4.9 [_flutterfire_internals collection firebase_core flutter meta plugin_platform_interface]
- firebase_auth_web 5.13.4 [firebase_auth_platform_interface firebase_core firebase_core_web flutter flutter_web_plugins http_parser meta web]
- firebase_core_platform_interface 5.3.0 [collection flutter flutter_test meta plugin_platform_interface]
- firebase_core_web 2.18.1 [firebase_core_platform_interface flutter flutter_web_plugins meta web]
- firebase_crashlytics_platform_interface 3.6.46 [_flutterfire_internals collection firebase_core flutter meta plugin_platform_interface]
- firebase_database_platform_interface 0.2.5+46 [_flutterfire_internals collection firebase_core flutter meta plugin_platform_interface]
- firebase_database_web 0.2.6+4 [collection firebase_core firebase_core_web firebase_database_platform_interface flutter flutter_web_plugins]
- firebase_in_app_messaging_platform_interface 0.2.4+46 [_flutterfire_internals firebase_core flutter meta plugin_platform_interface]
- firebase_messaging_platform_interface 4.5.48 [_flutterfire_internals firebase_core flutter meta plugin_platform_interface]
- firebase_messaging_web 3.9.4 [_flutterfire_internals firebase_core firebase_core_web firebase_messaging_platform_interface flutter flutter_web_plugins meta web]
- firebase_performance_platform_interface 0.1.4+46 [_flutterfire_internals firebase_core flutter plugin_platform_interface]
- firebase_performance_web 0.1.7+4 [_flutterfire_internals firebase_core firebase_core_web firebase_performance_platform_interface flutter flutter_web_plugins]
- firebase_remote_config_platform_interface 1.4.46 [_flutterfire_internals firebase_core flutter meta plugin_platform_interface]
- firebase_remote_config_web 1.7.4 [firebase_core firebase_core_web firebase_remote_config_platform_interface flutter flutter_web_plugins]
- firebase_storage_platform_interface 5.1.33 [_flutterfire_internals collection firebase_core flutter meta plugin_platform_interface]
- firebase_storage_web 3.10.5 [_flutterfire_internals async firebase_core firebase_core_web firebase_storage_platform_interface flutter flutter_web_plugins http meta web]
- fixnum 1.1.1
- flutter_cache_manager 3.4.1 [clock collection file flutter http path path_provider rxdart sqflite uuid]
- flutter_image_compress 2.3.0 [flutter flutter_image_compress_platform_interface flutter_image_compress_common flutter_image_compress_web flutter_image_compress_macos flutter_image_compress_ohos]
- flutter_image_compress_common 1.0.5 [flutter flutter_image_compress_platform_interface]
- flutter_image_compress_macos 1.0.2 [flutter flutter_image_compress_platform_interface]
- flutter_image_compress_ohos 0.0.3 [flutter flutter_image_compress_platform_interface]
- flutter_image_compress_platform_interface 1.0.5 [flutter plugin_platform_interface cross_file]
- flutter_image_compress_web 0.1.4+1 [flutter flutter_web_plugins flutter_image_compress_platform_interface js]
- flutter_plugin_android_lifecycle 2.0.23 [flutter]
- flutter_secure_storage_linux 1.2.1 [flutter flutter_secure_storage_platform_interface]
- flutter_secure_storage_macos 3.1.2 [flutter flutter_secure_storage_platform_interface]
- flutter_secure_storage_platform_interface 1.1.2 [flutter plugin_platform_interface]
- flutter_secure_storage_web 1.2.1 [flutter flutter_secure_storage_platform_interface flutter_web_plugins js]
- flutter_secure_storage_windows 3.1.2 [ffi flutter flutter_secure_storage_platform_interface path path_provider win32]
- flutter_web_plugins 0.0.0 [flutter characters collection material_color_utilities meta vector_math]
- font_awesome_flutter 9.2.0 [flutter]
- google_identity_services_web 0.3.3 [meta web]
- google_sign_in 6.2.2 [flutter google_sign_in_android google_sign_in_ios google_sign_in_platform_interface google_sign_in_web]
- google_sign_in_android 6.1.33 [flutter google_sign_in_platform_interface]
- google_sign_in_ios 5.7.8 [flutter google_sign_in_platform_interface]
- google_sign_in_platform_interface 2.4.5 [flutter plugin_platform_interface]
- google_sign_in_web 0.12.4+3 [flutter flutter_web_plugins google_identity_services_web google_sign_in_platform_interface http web]
- graphs 2.3.2 [collection]
- gtk 2.1.0 [ffi flutter meta]
- html 0.15.5 [csslib source_span]
- http_client_helper 3.0.0 [http]
- http_parser 4.0.2 [collection source_span string_scanner typed_data]
- image 4.3.0 [archive meta xml]
- image_editor_common 1.2.0 [flutter image_editor_platform_interface]
- image_editor_ohos 0.0.9 [flutter image_editor_platform_interface]
- image_editor_platform_interface 1.1.0 [flutter platform plugin_platform_interface]
- image_picker_android 0.8.12+17 [flutter flutter_plugin_android_lifecycle image_picker_platform_interface]
- image_picker_for_web 3.0.6 [flutter flutter_web_plugins image_picker_platform_interface mime web]
- image_picker_ios 0.8.12+1 [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.10.0 [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]
- in_app_review_platform_interface 2.0.5 [flutter url_launcher plugin_platform_interface platform]
- intl 0.19.0 [clock meta path]
- js 0.6.7 [meta]
- json_annotation 4.9.0 [meta]
- leak_tracker 10.0.5 [clock collection meta path vm_service]
- leak_tracker_flutter_testing 3.0.5 [flutter leak_tracker leak_tracker_testing matcher meta]
- leak_tracker_testing 3.0.1 [leak_tracker matcher meta]
- linkify 5.0.0
- lints 5.0.0
- matcher 0.12.16+1 [async meta stack_trace term_glyph test_api]
- material_color_utilities 0.11.1 [collection]
- meta 1.15.0
- nested 1.0.0 [flutter]
- nm 0.5.0 [dbus]
- octo_image 2.1.0 [flutter]
- package_info_plus_platform_interface 3.0.1 [flutter meta plugin_platform_interface]
- path 1.9.0
- path_parsing 1.1.0 [meta vector_math]
- path_provider_android 2.2.12 [flutter path_provider_platform_interface]
- path_provider_foundation 2.4.0 [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.2 [flutter platform plugin_platform_interface]
- path_provider_windows 2.3.0 [ffi flutter path path_provider_platform_interface]
- permission_handler_android 12.0.13 [flutter permission_handler_platform_interface]
- permission_handler_apple 9.4.5 [flutter permission_handler_platform_interface]
- permission_handler_html 0.1.3+5 [flutter flutter_web_plugins permission_handler_platform_interface web]
- permission_handler_platform_interface 4.2.3 [flutter meta plugin_platform_interface]
- permission_handler_windows 0.2.1 [flutter permission_handler_platform_interface]
- petitparser 6.0.2 [meta]
- platform 3.1.6
- plugin_platform_interface 2.1.8 [meta]
- qr 3.0.2 [meta]
- rive_common 0.4.13 [collection ffi flutter flutter_web_plugins graphs http meta plugin_platform_interface web]
- rxdart 0.28.0
- share_plus_platform_interface 5.0.1 [cross_file flutter meta mime plugin_platform_interface path_provider uuid]
- shared_preferences_android 2.3.3 [flutter shared_preferences_platform_interface]
- shared_preferences_foundation 2.5.3 [flutter shared_preferences_platform_interface]
- shared_preferences_linux 2.4.1 [file flutter path path_provider_linux path_provider_platform_interface shared_preferences_platform_interface]
- shared_preferences_platform_interface 2.4.1 [flutter plugin_platform_interface]
- shared_preferences_web 2.4.2 [flutter flutter_web_plugins shared_preferences_platform_interface web]
- shared_preferences_windows 2.4.1 [file flutter path path_provider_platform_interface path_provider_windows shared_preferences_platform_interface]
- sky_engine 0.0.99
- source_span 1.10.0 [collection path term_glyph]
- sprintf 7.0.0
- sqflite 2.4.1 [flutter sqflite_android sqflite_darwin sqflite_platform_interface sqflite_common path]
- sqflite_android 2.4.0 [flutter sqflite_common path sqflite_platform_interface]
- sqflite_common 2.5.4+6 [synchronized path meta]
- sqflite_darwin 2.4.1 [flutter sqflite_platform_interface meta sqflite_common path]
- sqflite_platform_interface 2.4.0 [flutter platform sqflite_common plugin_platform_interface meta]
- stack_trace 1.11.1 [path]
- stream_channel 2.1.2 [async]
- string_scanner 1.2.0 [source_span]
- synchronized 3.3.0+3
- term_glyph 1.2.1
- test_api 0.7.2 [async boolean_selector collection meta source_span stack_trace stream_channel string_scanner term_glyph]
- typed_data 1.4.0 [collection]
- universal_io 2.2.2 [collection meta typed_data]
- url_launcher_android 6.3.14 [flutter url_launcher_platform_interface]
- url_launcher_ios 6.3.1 [flutter url_launcher_platform_interface]
- url_launcher_linux 3.2.1 [flutter url_launcher_platform_interface]
- url_launcher_macos 3.2.1 [flutter url_launcher_platform_interface]
- url_launcher_platform_interface 2.3.2 [flutter plugin_platform_interface]
- url_launcher_web 2.3.3 [flutter flutter_web_plugins url_launcher_platform_interface web]
- url_launcher_windows 3.1.3 [flutter url_launcher_platform_interface]
- vector_graphics 1.1.15 [flutter http vector_graphics_codec]
- vector_graphics_codec 1.1.12
- vector_graphics_compiler 1.1.16 [args meta path path_parsing vector_graphics_codec xml]
- vector_math 2.1.4
- video_compress 3.1.1 [flutter]
- video_player_android 2.7.16 [flutter video_player_platform_interface]
- video_player_avfoundation 2.6.3 [flutter video_player_platform_interface]
- video_player_platform_interface 6.2.3 [flutter plugin_platform_interface]
- video_player_web 2.3.3 [flutter flutter_web_plugins video_player_platform_interface web]
- video_thumbnail 0.5.3 [flutter]
- vm_service 14.2.5
- web 1.1.0
- webview_flutter 4.9.0 [flutter webview_flutter_android webview_flutter_platform_interface webview_flutter_wkwebview]
- webview_flutter_android 3.16.9 [flutter webview_flutter_platform_interface]
- webview_flutter_platform_interface 2.10.0 [flutter meta plugin_platform_interface]
- webview_flutter_wkwebview 3.16.3 [flutter path webview_flutter_platform_interface]
- win32 5.8.0 [ffi]
- xdg_directories 1.1.0 [meta path]
- xml 6.5.0 [collection meta petitparser]
- yaml 3.1.2 [collection source_span string_scanner]

Additional context and comments

No response

@Tom3652 Tom3652 added Needs Attention This issue needs maintainer attention. type: bug Something isn't working labels Nov 25, 2024
@SelaseKay SelaseKay added plugin: auth platform: android Issues / PRs which are specifically for Android. platform: ios Issues / PRs which are specifically for iOS. labels Nov 27, 2024
@SelaseKay
Copy link
Contributor

Hi @Tom3652, thanks for the report. Unfortunately, I couldn’t reproduce this issue on my end. It's unfortunate that you’re unable to reproduce it locally as well. Providing a fully reproducible sample would be incredibly helpful in diagnosing the problem.

@SelaseKay SelaseKay added blocked: customer-response Waiting for customer response, e.g. more information was requested. resolution: needs-repro This issue could not be reproduced or needs an up to date reproduction on latest FlutterFire plugin. and removed Needs Attention This issue needs maintainer attention. labels Nov 28, 2024
@Tom3652
Copy link
Author

Tom3652 commented Nov 28, 2024

Hi @SelaseKay yes i know believe me i wish i had a reproductible use case...
But that's something you can see through a large user base only i guess, i have more or less 30k calls in Cloud Functions each day and i have few hundreds of errors.

Note : i have two ideas for this problem, i have put only the first one in my next release tonight :

  1. Forcing refresh if without refresh the token is empty :
  Future<String> getIdToken({bool forceRefresh = false}) async {
    String idToken = "";
    try {
      if (_currentUser != null) {
        idToken = await FirebaseAuth.instance.currentUser!.getIdToken(forceRefresh) ?? "";
      }
    } catch (error) {
      print("Could not get id token of user $error");
      // This records a Crashlytics error non fatal
      AnalyticsAPI.logError(error, reason: "Could not get id token of current user");
    }
     if (_idToken.isEmpty && !forceRefresh) {
      return initToken(forceRefresh: true);
    }
   return idToken;
  }

This way, if it's empty by any ways without forcing the refresh, it will force it and send it.

  1. Refreshing the token after each request to the cloud function without awaiting it.

I will keep updating here if i find a solution, but once again maybe it's not a bug and that's the expected behavior and i a am simply using it in a incorrect way...

Thanks for your time anyway !

@google-oss-bot google-oss-bot added Needs Attention This issue needs maintainer attention. and removed blocked: customer-response Waiting for customer response, e.g. more information was requested. labels Nov 28, 2024
@luis-cruzt
Copy link

Hello, we are experiencing the same issue, it looks like it's only reproducible on 10k+ calls, our project has a range of 10k - 40k calls.

For now we are going to force the refresh token if it's empty and come back with the results.

@Tom3652
Copy link
Author

Tom3652 commented Nov 29, 2024

I have a bit more information, i have checked my crashlytics logs and seen actually plenty of logs :

[firebase_auth/network-request-failed] Network error (such as timeout, interrupted connection or unreachable host) has occurred.. Error thrown Could not get id token of user.

So that can explain some of the logs.
However, if the users would actually not have an active internet connection, my backend would not be reached in matter of milliseconds after the getIdToken.

I wonder then if there are some real network issues or if the users are "terminating" the app during the request, but once again my backend would not be reached in that case...

I have an expired token because my var idToken is actually global in my real app and thus, if the getIdToken method throws the network error, my idToken remains "old" and not empty and i see the token expired error in my cloud function.

So my new function looks like this :

  String _idToken = "";

  User? get _currentUser => FirebaseAuth.instance.currentUser;

  /// Handle the fact the token is refreshed
  Future<void> initToken({bool forceRefresh = false}) async {
    if (forceRefresh) {
      LogManager.printDebug("Forcing token refresh...");
      AnalyticsAPI.logEvent("refresh_id_token_forced");
    }
    else {
      AnalyticsAPI.logEvent("refresh_id_token");
    }
    try {
      if (_currentUser != null) {
        String newToken = await _currentUser!.getIdToken(forceRefresh) ?? "";
        if (newToken.isNotEmpty) {
          _idToken = newToken;
        }
        else {
          AnalyticsAPI.logError("[initToken]: New id token is empty.");
          if (!forceRefresh) {
            await initToken(forceRefresh: true);
          }
        }
      }
      else {
        AnalyticsAPI.logError("[initToken]: Current user is null.");
      }
    } catch (error) {
      LogManager.printDebug("Could not get id token of user $error");
      AnalyticsAPI.logError(error,
          reason: "Could not get id token of user.");
    }
  }

I am going to release that tonight and see how is it going then, will keep updating.

@Tom3652
Copy link
Author

Tom3652 commented Dec 6, 2024

This has helped to see much more errors that i will list here, but didn't help to fix the issue.
I have many errors but most of them are network errors i think so less important.

I have improved my logging by : AnalyticsAPI.logError(error, reason: "Could not get id token of user with refresh $forceRefresh");

The main weird error on Android (not iOS so far unless i have missed it) that occurred :

Capture d’écran 2024-12-06 à 11 53 03
[firebase_auth/unknown] An internal error has occurred. [ Json conversion failed! Failed to parse error for string [<!DOCTYPE html><html lang=en> <meta charset=utf-8> <meta name=viewport content="initial-scale=1, minimum-scale=1, width=device-width"> <title>Error 403 (Forbidden)!!1</title> <style> *{margin:0;padding:0}html,code{font:15px/22px arial,sans-serif}html{background:#fff;color:#222;padding:15px}body{margin:7% auto 0;max-width:390px;min-height:180px;padding:30px 0 15px}* > body{background:url(//www.google.com/images/errors/robot.png) 100% 5px no-repeat;padding-right:205px}p{margin:11px 0 22px;overflow:hidden}ins{color:#777;text-decoration:none}a img{border:0}@media screen and (max-width:772px){body{background:none;margin-top:0;max-width:none;padding-right:0}}#logo{background:url(//www.google.com/images/branding/googlelogo/1x/googlelogo_color_150x54dp.png) no-repeat;margin-left:-5px}@media only screen and (min-resolution:192dpi){#logo{background:url(//www.google.com/images/branding/googlelogo/2x/googlelogo_color_150x54dp.png) no-repeat 0% 0%/100% 100%;-moz-border-image:url(//www.google.com/images/branding/googlelogo/2x/googlelogo_color_150x54dp.png) 0}}@media only screen and (-webkit-min-device-pixel-ratio:2){#logo{background:url(//www.google.com/images/branding/googlelogo/2x/googlelogo_color_150x54dp.png) no-repeat;-webkit-background-size:100% 100%}}#logo{display:inline-block;height:54px;width:150px} </style> <a href=//www.google.com/><span id=logo aria-label=Google></span></a> <p><b>403.</b> <ins>That’s an error.</ins> <p>Your client does not have permission to get URL <code>/v1/token</code> from this server. <ins>That’s all we know.</ins>]. Error thrown Could not get id token of user with refresh true.

All the various network errors :

[firebase_auth/unknown] Failure in SSL library, usually a protocol error error:100000d7:SSL routines:OPENSSL_internal:SSL_HANDSHAKE_FAILURE (third_party/openssl/boringssl/src/ssl/ssl_lib.cc:996 0x702d2477dc:0x00000000). Error thrown Could not get id token of user j9WezqXUuHZge2USdhd2SbhrJQz2 with refresh false.

[firebase_auth/network-request-failed] A network error (such as timeout, interrupted connection or unreachable host) has occurred.. Error thrown Could not get id token of user with refresh false.
[firebase_auth/unknown] I/O error during system call, Connection reset by peer. Error thrown Could not get id token of user with refresh true.
[firebase_auth/unknown] The user's credential is no longer valid. The user must sign in again.. Error thrown Could not get id token of user with refresh false.
[firebase_auth/unknown] An internal error has occurred. [ unexpected end of stream on com.android.okhttp.Address@c82eae1c. Error thrown Could not get id token of user with refresh true.

@kruimeldiev
Copy link

We're having the same issue with our app as wel. Based on user feedback we've gathered, we've found that users get signed out of the app. The following network error gets logged a couple dozen times a day (we have somewhere about ~10K to ~20K active daily users).
[firebase_auth/network-request-failed] Network error (such as timeout, interrupted connection or unreachable host) has occurred.. Error thrown Could not get id token of user.
We have a check in the app that listens for network connectivity, so if the user would not be connected, out server should not be reached.

@SelaseKay
Copy link
Contributor

Hi @Tom3652, thanks for the additional feedback. What authentication methods do you use in your app?

@SelaseKay SelaseKay added blocked: customer-response Waiting for customer response, e.g. more information was requested. and removed Needs Attention This issue needs maintainer attention. labels Dec 10, 2024
@Tom3652
Copy link
Author

Tom3652 commented Dec 10, 2024

Hi @SelaseKay , i am using the Sign in With Apple & with Google only.
I am using the AppleAuthProvider class for Apple, and the flutter package sign_in_with_google as an OAuthProvider.

  Future<LoginResult> signInWithApple() async {
    AppleAuthProvider appleAuthProvider = AppleAuthProvider();
    appleAuthProvider.addScope("email");
    appleAuthProvider.addScope("fullName");
    return _signInWithProvider(provider: appleAuthProvider);
  }
  final GoogleSignIn _googleSignIn = GoogleSignIn(scopes: ['profile', 'email']);

  Future<OAuthCredential?> _signInWithGoogle() async {
    final GoogleSignInAccount? googleUser = await _googleSignIn.signIn();
    if (googleUser == null) return null;
    debugPrint("Google user got : ${googleUser.email}");

    // Obtain the auth details from the request
    final GoogleSignInAuthentication googleAuth =
    await googleUser.authentication;

    debugPrint("Google auth : ${googleAuth.idToken!}");

    // Create a new credential
    final OAuthCredential credential = GoogleAuthProvider.credential(
      accessToken: googleAuth.accessToken,
      idToken: googleAuth.idToken,
    );
    return credential;
  }

  Future<LoginResult> signInWithGoogle() async {
    OAuthCredential? credential = await _signInWithGoogle();
    return _signInWithProvider(credential: credential);
  }
 Future<LoginResult> _signInWithProvider(
      {AuthProvider? provider, OAuthCredential? credential}) async {
    _loginResult.reset();
    try {
      UserCredential? userCredential = provider != null
          ? await FirebaseAuth.instance.signInWithProvider(provider)
          : credential != null
          ? await FirebaseAuth.instance.signInWithCredential(credential)
          : null;
      if (userCredential?.user != null) {
        _loginResult.onSuccess();
      }
    } on FirebaseAuthException {
      _loginResult.setError(ErrorState.userDisabled);
    } on Exception {
      _loginResult.setError(ErrorState.generic);
    }
    return _loginResult;
  }

@google-oss-bot google-oss-bot added Needs Attention This issue needs maintainer attention. and removed blocked: customer-response Waiting for customer response, e.g. more information was requested. labels Dec 10, 2024
@AbhishekDoshi26
Copy link

Faced the same issue. We are using email link sign in, google and apple. It's completely random but if it happens for a particular user, it keeps on happening. One of our prod users complained about this and we were not able to trace it down because locally it's not reproducible. I feel there were some API changes (internally) because earlier everything was working fine. We also got the user bug report around a week ago. Our use case was that we were sending the token to our backend and luckily due to backend logs, we were able to catch the bug! As of now, the only solution (assuming) is to forceRefresh

@SelaseKay
Copy link
Contributor

Hi @AbhishekDoshi26, I agree. This could be coming from upstream. I've been trying to reproduce this locally but haven't made much progress.

@Tom3652
Copy link
Author

Tom3652 commented Dec 19, 2024

I am adding a new error log to the above ones still getting the ID Token :

[firebase_auth/internal-error] An internal error has occurred, print and inspect the error details for more information..

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Needs Attention This issue needs maintainer attention. platform: android Issues / PRs which are specifically for Android. platform: ios Issues / PRs which are specifically for iOS. plugin: auth resolution: needs-repro This issue could not be reproduced or needs an up to date reproduction on latest FlutterFire plugin. type: bug Something isn't working
Projects
None yet
Development

No branches or pull requests

6 participants