darwin-morocho / flutter-facebook-auth

A flutter plugin to add login with facebook in your flutter app
197 stars 138 forks source link

IOS Only : - Invalid OAuth access token - Cannot parse access token #419

Open khushal-chothani opened 1 month ago

khushal-chothani commented 1 month ago

What version are you using?

flutter_facebook_auth: ^6.0.3.

What OS and version are you using to local deploy your application?

macOs 14.6.1

What platforms are you seeing the problem on?

iOS

pubspec.yaml

environment:
  sdk: '>=3.1.5 <4.0.0'

dependencies:
  flutter:
    sdk: flutter

  firebase_auth: ^4.5.0
  firebase_core: ^2.24.2
  firebase_messaging: ^14.7.19
  firebase_database: ^10.4.9
  firebase_app_check: ^0.2.2+1
  flutter_facebook_auth: ^6.0.3

Describe the Bug

image

image

When using facebook login method i'm facing issue related to token

this is my code

Future signInWithFacebook() async { try { final LoginResult loginResult = await FacebookAuth.instance.login(permissions: ['public_profile']);

  if (loginResult.status == LoginStatus.success) {
    final OAuthCredential facebookAuthCredential = FacebookAuthProvider.credential(loginResult.accessToken!.token);
    var cred = await FirebaseAuth.instance.signInWithCredential(facebookAuthCredential);

    print(cred);
  }
} on Exception catch (e) {

  print(e);
}

}

Expected Behavior

Expected behaviour is token should be valid and it should be login in using facebook

To Reproduce

To Reproduce Use given or even latest package Do setup in IOS

Then when we use facebook login method then first it will create login result then after creating AuthCredential pass that cred to signInWithCredential method and facing this issue in IOS only

Relevant log output

flutter: [firebase_auth/invalid-credential] {"code":190,"message":"Invalid OAuth access token - Cannot parse access token"}

flutter doctor -v

Flutter (Channel stable, 3.22.2, on macOS 14.6.1 23G93 darwin-arm64, locale en-IN)
    • Flutter version 3.22.2 on channel stable at /Users/khushal/Development/SDK/flutter
    • Upstream repository https://github.com/flutter/flutter.git
    • Framework revision 761747bfc5 (9 weeks ago), 2024-06-05 22:15:13 +0200
    • Engine revision edd8546116
    • Dart version 3.4.3
    • DevTools version 2.34.3

[✓] Android toolchain - develop for Android devices (Android SDK version 34.0.0)
    • Android SDK at /Users/khushal/Library/Android/sdk
    • Platform android-34, build-tools 34.0.0
    • ANDROID_HOME = /Users/khushal/Library/Android/sdk
    • Java binary at: /Applications/Android Studio.app/Contents/jbr/Contents/Home/bin/java
    • Java version OpenJDK Runtime Environment (build 17.0.11+0-17.0.11b1207.24-11852314)
    • All Android licenses accepted.

[✓] Xcode - develop for iOS and macOS (Xcode 15.4)
    • Xcode at /Applications/Xcode.app/Contents/Developer
    • Build 15F31d
    • CocoaPods version 1.15.2

[✓] Chrome - develop for the web
    • Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome

[✓] Android Studio (version 2024.1)
    • Android Studio at /Applications/Android Studio.app/Contents
    • Flutter plugin can be installed from:
      🔨 https://plugins.jetbrains.com/plugin/9212-flutter
    • Dart plugin can be installed from:
      🔨 https://plugins.jetbrains.com/plugin/6351-dart
    • Java version OpenJDK Runtime Environment (build 17.0.11+0-17.0.11b1207.24-11852314)

[✓] VS Code (version 1.92.0)
    • VS Code at /Applications/Visual Studio Code.app/Contents
    • Flutter extension version 3.94.0

[✓] Connected device (4 available)
    • iPhone 15 (mobile)              • DFD4EEBC-24F2-4079-BB33-9C2A676D1CE8 • ios            • com.apple.CoreSimulator.SimRuntime.iOS-17-5 (simulator)
    • macOS (desktop)                 • macos                                • darwin-arm64   • macOS 14.6.1 23G93 darwin-arm64
    • Mac Designed for iPad (desktop) • mac-designed-for-ipad                • darwin         • macOS 14.6.1 23G93 darwin-arm64
    • Chrome (web)                    • chrome                               • web-javascript • Google Chrome 127.0.6533.100

[✓] Network resources
    • All expected network resources are available.

• No issues found!

Info.plist (iOS)

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>BGTaskSchedulerPermittedIdentifiers</key>
    <array>
        <string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
    </array>
    <key>CADisableMinimumFrameDurationOnPhone</key>
    <true/>
    <key>CFBundleDevelopmentRegion</key>
    <string>$(DEVELOPMENT_LANGUAGE)</string>
    <key>CFBundleDisplayName</key>
    <string>MY APP NAME</string>
    <key>CFBundleExecutable</key>
    <string>$(EXECUTABLE_NAME)</string>
    <key>CFBundleIdentifier</key>
    <string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
    <key>CFBundleInfoDictionaryVersion</key>
    <string>6.0</string>
    <key>CFBundleName</key>
    <string>MY APP NAME</string>
    <key>CFBundlePackageType</key>
    <string>APPL</string>
    <key>CFBundleShortVersionString</key>
    <string>$(MARKETING_VERSION)</string>
    <key>CFBundleSignature</key>
    <string>????</string>
    <key>CFBundleURLTypes</key>
    <array>
        <dict>
            <key>CFBundleTypeRole</key>
            <string>Editor</string>
            <key>CFBundleURLSchemes</key>
            <array>
                <string>fb{My-fb-app-id}</string>
                <string>com.googleusercontent.apps.-----------</string>
            </array>
        </dict>
        <dict>
            <key>CFBundleTypeRole</key>
            <string>Editor</string>
            <key>CFBundleURLName</key>
            <string>app.example</string>
            <key>CFBundleURLSchemes</key>
            <array>
                <string>test</string>
            </array>
        </dict>
    </array>
    <key>CFBundleVersion</key>
    <string>$(CURRENT_PROJECT_VERSION)</string>
    <key>FLTEnableImpeller</key>
    <false/>
    <key>FacebookAdvertiserIDCollectionEnabled</key>
    <false/>
    <key>FacebookAppID</key>
    <string>{My-fb-app-id}</string>
    <key>FacebookAutoInitEnabled</key>
    <true/>
    <key>FacebookAutoLogAppEventsEnabled</key>
    <true/>
    <key>FacebookClientToken</key>
    <string>c-token</string>
    <key>FacebookDisplayName</key>
    <string>Myapp</string>
    <key>FirebaseAppDelegateProxyEnabled</key>
    <false/>
    <key>GoogleUtilitiesAppDelegateProxyEnabled</key>
    <true/>
    <key>LSApplicationQueriesSchemes</key>
    <array>
        <string>app.example</string>
        <string>fbapi</string>
        <string>fbapi20130214</string>
        <string>fbapi20130410</string>
        <string>fbapi20130702</string>
        <string>fbapi20131010</string>
        <string>fbapi20131219</string>
        <string>fbapi20140410</string>
        <string>fbapi20140116</string>
        <string>fbapi20150313</string>
        <string>fbapi20150629</string>
        <string>fbapi20160328</string>
        <string>fbauth</string>
        <string>fb-messenger-share-api</string>
        <string>fbauth2</string>
        <string>fbshareextension</string>

    </array>
    <key>LSRequiresIPhoneOS</key>
    <true/>
    <key>NSAppTransportSecurity</key>
    <dict>
        <key>NSAllowsArbitraryLoads</key>
        <true/>
        <key>NSAllowsArbitraryLoadsForMedia</key>
        <true/>
        <key>NSExceptionDomains</key>
        <dict>
            <key>example.mp3</key>
            <dict>
                <key>NSIncludesSubdomains</key>
                <true/>
                <key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key>
                <true/>
                <key>NSTemporaryExceptionMinimumTLSVersion</key>
                <string>TLSv1.1</string>
            </dict>
        </dict>
    </dict>
    <key>NSBonjourServices</key>
    <array>
        <string>_dartobservatory._tcp</string>
    </array>
    <key>NSMicrophoneUsageDescription</key>
    <string>Need microphone access for uploading videos</string>
    <key>UIApplicationSupportsIndirectInputEvents</key>
    <true/>
    <key>UIBackgroundModes</key>
    <array>
        <string>fetch</string>
        <string>processing</string>
        <string>remote-notification</string>
    </array>
    <key>UILaunchStoryboardName</key>
    <string>LaunchScreen</string>
    <key>UIMainStoryboardFile</key>
    <string>Main</string>
    <key>UIStatusBarHidden</key>
    <false/>
    <key>UISupportedInterfaceOrientations</key>
    <array>
        <string>UIInterfaceOrientationPortrait</string>
    </array>
    <key>UISupportedInterfaceOrientations~ipad</key>
    <array>
        <string>UIInterfaceOrientationPortrait</string>
        <string>UIInterfaceOrientationPortraitUpsideDown</string>
        <string>UIInterfaceOrientationLandscapeLeft</string>
        <string>UIInterfaceOrientationLandscapeRight</string>
    </array>
    <key>UIViewControllerBasedStatusBarAppearance</key>
    <false/>
    <key>com.apple.security.network.client</key>
    <true/>
    <key>io.flutter.embedded_views_preview</key>
    <string>YES</string>
</dict>
</plist>

Podfile (iOS)

# Uncomment this line to define a global platform for your project
platform :ios, '12.0'

# CocoaPods analytics sends network stats synchronously affecting flutter build latency.
ENV['COCOAPODS_DISABLE_STATS'] = 'true'

project 'Runner', {
  'Debug' => :debug,
  'Profile' => :release,
  'Release' => :release,
}

def flutter_root
  generated_xcode_build_settings_path = File.expand_path(File.join('..', 'Flutter', 'Generated.xcconfig'), __FILE__)
  unless File.exist?(generated_xcode_build_settings_path)
    raise "#{generated_xcode_build_settings_path} must exist. If you're running pod install manually, make sure flutter pub get is executed first"
  end

  File.foreach(generated_xcode_build_settings_path) do |line|
    matches = line.match(/FLUTTER_ROOT\=(.*)/)
    return matches[1].strip if matches
  end
  raise "FLUTTER_ROOT not found in #{generated_xcode_build_settings_path}. Try deleting Generated.xcconfig, then run flutter pub get"
end

require File.expand_path(File.join('packages', 'flutter_tools', 'bin', 'podhelper'), flutter_root)

flutter_ios_podfile_setup

target 'Runner' do
  use_frameworks!
  use_modular_headers!

  flutter_install_all_ios_pods File.dirname(File.realpath(__FILE__))
end

post_install do |installer|
  installer.aggregate_targets.each do |target|
    target.xcconfigs.each do |variant, xcconfig|
    xcconfig_path = target.client_root + target.xcconfig_relative_path(variant)
    IO.write(xcconfig_path, IO.read(xcconfig_path).gsub("DT_TOOLCHAIN_DIR", "TOOLCHAIN_DIR"))
    end
  end
  installer.pods_project.targets.each do |target|
     flutter_additional_ios_build_settings(target)
     target.build_configurations.each do |config|
      if config.base_configuration_reference.is_a? Xcodeproj::Project::Object::PBXFileReference
        xcconfig_path = config.base_configuration_reference.real_path
        IO.write(xcconfig_path, IO.read(xcconfig_path).gsub("DT_TOOLCHAIN_DIR", "TOOLCHAIN_DIR"))
      end
      config.build_settings['IPHONEOS_DEPLOYMENT_TARGET'] = '12.0'

      # You can enable the permissions needed here. For example to enable camera
      # permission, just remove the `#` character in front so it looks like this:
      #
      # ## dart: PermissionGroup.camera
      # 'PERMISSION_CAMERA=1'
      #
      #  Preprocessor definitions can be found in: https://github.com/Baseflow/flutter-permission-handler/blob/master/permission_handler_apple/ios/Classes/PermissionHandlerEnums.h
      config.build_settings['GCC_PREPROCESSOR_DEFINITIONS'] ||= [
        '$(inherited)',

        ## dart: PermissionGroup.calendar
        # 'PERMISSION_EVENTS=1',

        ## dart: PermissionGroup.reminders
        # 'PERMISSION_REMINDERS=1',

        ## dart: PermissionGroup.contacts
        # 'PERMISSION_CONTACTS=1',

        ## dart: PermissionGroup.camera
        # 'PERMISSION_CAMERA=1',

        ## dart: PermissionGroup.microphone
        # 'PERMISSION_MICROPHONE=1',

        ## dart: PermissionGroup.speech
        # 'PERMISSION_SPEECH_RECOGNIZER=1',

        ## dart: PermissionGroup.photos
        # 'PERMISSION_PHOTOS=1',

        ## dart: [PermissionGroup.location, PermissionGroup.locationAlways, PermissionGroup.locationWhenInUse]
        # 'PERMISSION_LOCATION=1',

        ## dart: PermissionGroup.notification
        'PERMISSION_NOTIFICATIONS=1',

        ## dart: PermissionGroup.mediaLibrary
        # 'PERMISSION_MEDIA_LIBRARY=1',

        ## dart: PermissionGroup.sensors
        # 'PERMISSION_SENSORS=1',   

        ## dart: PermissionGroup.bluetooth
        # 'PERMISSION_BLUETOOTH=1',

        ## dart: PermissionGroup.appTrackingTransparency
        # 'PERMISSION_APP_TRACKING_TRANSPARENCY=1',

        ## dart: PermissionGroup.criticalAlerts
        # 'PERMISSION_CRITICAL_ALERTS=1'
      ]

    end 
  end
end

AndroidManifest.xml

.

MainActivity.java

.

MainActivity.kt

.

index.html

.

Info.plist (macOS)

.
darwin-morocho commented 1 month ago

@khushal-chothani https://github.com/darwin-morocho/flutter-facebook-auth/issues/397#issuecomment-2099740411

khushal-chothani commented 4 weeks ago

Hi @darwin-morocho

I checked that code and i used code which in example of this repo

Future _login() async { _nonce = generateNonce();

setState(() {
  _state = LoginLoading();
});
final result = await _auth.login(
  loginTracking: LoginTracking.limited,
  nonce: _nonce,
);

switch (result.status) {
  case LoginStatus.success:
    await _getUserProfile(result.accessToken!);
    AuthCredential credential = FacebookAuthProvider.credential(result.accessToken!.tokenString);
    UserCredential user =  await FirebaseAuth.instance.signInWithCredential(credential);
    print(user);
  case LoginStatus.cancelled:
  case _:
    log(
      '${result.status.name}: ${result.message}',
    );
    setState(() {
      _state = LoginNotAuthenticated();
    });
}

}

here additional line is

AuthCredential credential = FacebookAuthProvider.credential(result.accessToken!.tokenString); UserCredential user = await FirebaseAuth.instance.signInWithCredential(credential); print(user);

Which throws error - [firebase_auth/invalid-credential] {"code":190,"message":"Bad signature"} So plugin works but it's giving the wrong token or i am not sure but firebase core rejecting for signInWithCredential login and throws : - [firebase_auth/invalid-credential] {"code":190,"message":"Bad signature"}

darwin-morocho commented 4 weeks ago

Hi @darwin-morocho

I checked that code and i used code which in example of this repo

Future _login() async {

_nonce = generateNonce();

setState(() {

  _state = LoginLoading();

});

final result = await _auth.login(

  loginTracking: LoginTracking.limited,

  nonce: _nonce,

);

switch (result.status) {

  case LoginStatus.success:

    await _getUserProfile(result.accessToken!);

    AuthCredential credential = FacebookAuthProvider.credential(result.accessToken!.tokenString);

    UserCredential user =  await FirebaseAuth.instance.signInWithCredential(credential);

    print(user);

  case LoginStatus.cancelled:

  case _:

    log(

      '${result.status.name}: ${result.message}',

    );

    setState(() {

      _state = LoginNotAuthenticated();

    });

}

}

here additional line is

AuthCredential credential = FacebookAuthProvider.credential(result.accessToken!.tokenString);

   UserCredential user =  await FirebaseAuth.instance.signInWithCredential(credential);

   print(user);

Which throws error - [firebase_auth/invalid-credential] {"code":190,"message":"Bad signature"}

So plugin works but it's giving the wrong token or i am not sure but firebase core rejecting for signInWithCredential login and throws : - [firebase_auth/invalid-credential] {"code":190,"message":"Bad signature"}

The example code is not valid for firebase auth. You need to pass to firebase the raw nonce.

https://github.com/darwin-morocho/flutter-facebook-auth/issues/397#issuecomment-2187411186