aws-amplify / amplify-flutter

A declarative library with an easy-to-use interface for building Flutter applications on AWS.
https://docs.amplify.aws
Apache License 2.0
1.32k stars 246 forks source link

Unautheticated role graphql api 'Failed to retrieve authorization token' #2496

Closed ghi8GPA closed 1 year ago

ghi8GPA commented 1 year ago

Description

Unautheticated user is unable to query public graphql models, example:

type DPSettings @model @auth(rules: [
  {allow: public,operations: [read], provider: iam},
  {allow: private, operations: [read]},
]) {
  id: ID!
  value: String
}

api cli-input.json

{
  "version": 1,
  "serviceConfiguration": {
    "apiName": "XXX",
    "serviceName": "AppSync",
    "defaultAuthType": {
        "mode": "AMAZON_COGNITO_USER_POOLS",
        "cognitoUserPoolId": "XXXX"
    },
    "conflictResolution": {},
    "additionalAuthTypes": [
      {
      "mode": "AWS_IAM"
      }
    ]
  }
}

unauth IAM role has correct settings:

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Action": "appsync:GraphQL",
            "Resource": [
                "arn:aws:appsync:eu-central-1:XXX:apis/XXXX/types/Query/fields/getDPSettings",
            "Effect": "Allow"
        }
    ]
}

Authenticator widget:

@override
Widget build(BuildContext context) {
    Provider.of<ThemeState>(context, listen: false).loadTheme(context);
    return GestureDetector(
        onTap: () => FocusManager.instance.primaryFocus?.unfocus(),
        child: Authenticator(
            child: MaterialApp(
title: 'title'.tr(),
              theme: theme,
              darkTheme: darkTheme,
              themeMode: state.theme == null
                  ? ThemeMode.system
                  : state.theme == true
                      ? ThemeMode.dark
                      : ThemeMode.light,
              debugShowCheckedModeBanner: false,
              localizationsDelegates: context.localizationDelegates,
              supportedLocales: context.supportedLocales,
              locale: context.locale,
              onGenerateRoute: (settings) {
                late Widget page;
                if (settings.name!.startsWith(routePrefixCheckoutFlow)) {
                  final subRoute =
                      settings.name!.substring(routePrefixCheckoutFlow.length);
                  page = CheckoutFlow(
                    setupPageRoute: subRoute,
                  );
                }
                return MaterialPageRoute<dynamic>(
                  builder: (context) {
                    return page;
                  },
                  settings: settings,
                );
              },
              home: const _Main());

my configureAmplify method:

Future<void> _configureAmplify() async {
    try {
      final auth = AmplifyAuthCognito();
      final analytics = AmplifyAnalyticsPinpoint();
      final api = AmplifyAPI(modelProvider: ModelProvider.instance);
      final storage = AmplifyStorageS3();
      await Amplify.addPlugins([auth, analytics, api, storage]);

      await Amplify.configure(amplifyconfig);
    } on AmplifyAlreadyConfiguredException {
      safePrint(
          'Tried to reconfigure Amplify; this can occur when your app restarts on Android.');
    }
  }

call on api gives the following error:

 try {
      var api = await Amplify.API.query(
        request: ModelQueries.get(DPSettings.classType, 'XXX')).response;
      _googlePlacesApiKey = api.data?.value;
    } on ApiException catch(e) {
      safePrint(e);
    }

ApiException(message: Failed to retrieve authorization token., recoverySuggestion: , underlyingException: Impossibile completare l'operazione. (Errore Amplify.AuthError 6).)

Categories

Steps to Reproduce

  1. Create an amplify auth with unautheticated IAM role
  2. Create an amplify api (graphql) with IAM
  3. Create a model with public access

Screenshots

No response

Platforms

Android Device/Emulator API Level

No response

Environment

[✓] Flutter (Channel stable, 3.3.9, on macOS 13.0.1 22A400 darwin-arm, locale en-IT)
[!] Android toolchain - develop for Android devices (Android SDK version 33.0.1)
    ✗ cmdline-tools component is missing
      Run `path/to/sdkmanager --install "cmdline-tools;latest"`
      See https://developer.android.com/studio/command-line for more details.
    ✗ Android license status unknown.
      Run `flutter doctor --android-licenses` to accept the SDK licenses.
      See https://flutter.dev/docs/get-started/install/macos#android-setup for more details.
[✓] Xcode - develop for iOS and macOS (Xcode 14.1)
[✓] Chrome - develop for the web
[✓] Android Studio (version 2021.3)
[✓] VS Code (version 1.73.1)
[✓] Connected device (3 available)
[✓] HTTP Host Availability

! Doctor found issues in 1 category.

Dependencies

Dart SDK 2.18.5
Flutter SDK 3.3.9
dolce_paradiso_app 1.0.0+1

dependencies:
- amplify_analytics_pinpoint 0.6.10 [amplify_analytics_pinpoint_android amplify_analytics_pinpoint_ios amplify_core aws_common flutter meta]
- amplify_api 0.6.10 [amplify_api_android amplify_api_ios amplify_core amplify_flutter aws_common collection flutter meta plugin_platform_interface]
- amplify_auth_cognito 0.6.10 [amplify_auth_cognito_android amplify_auth_cognito_ios amplify_core aws_common collection flutter meta plugin_platform_interface]
- amplify_authenticator 0.2.4 [amplify_auth_cognito amplify_core amplify_flutter async aws_common collection flutter flutter_localizations intl stream_transform]
- amplify_flutter 0.6.10 [amplify_core amplify_datastore_plugin_interface amplify_flutter_android amplify_flutter_ios aws_common collection flutter meta plugin_platform_interface]
- amplify_storage_s3 0.6.10 [amplify_storage_s3_android amplify_storage_s3_ios amplify_core aws_common flutter meta plugin_platform_interface path_provider path]
- cached_network_image 3.2.2 [flutter flutter_cache_manager octo_image cached_network_image_platform_interface cached_network_image_web]
- cupertino_icons 1.0.5
- dismissible_page 0.7.3 [flutter]
- easy_localization 3.0.1 [flutter shared_preferences intl args path easy_logger flutter_localizations]
- firebase_core 2.3.0 [firebase_core_platform_interface firebase_core_web flutter meta]
- firebase_messaging 14.1.2 [firebase_core firebase_core_platform_interface firebase_messaging_platform_interface firebase_messaging_web flutter meta]
- flutter 0.0.0 [characters collection material_color_utilities meta vector_math sky_engine]
- flutter_datetime_picker 1.5.1 [flutter]
- flutter_google_places_sdk 0.3.2+2 [flutter flutter_plugin_android_lifecycle flutter_google_places_sdk_ios flutter_google_places_sdk_web flutter_google_places_sdk_platform_interface flutter_google_places_sdk_android]
- flutter_launcher_icons 0.11.0 [args checked_yaml cli_util image json_annotation path yaml]
- flutter_native_splash 2.2.15 [args flutter flutter_web_plugins js html image meta path universal_io xml yaml]
- flutter_quill 6.1.5 [flutter collection flutter_colorpicker flutter_keyboard_visibility quiver tuple url_launcher pedantic characters diff_match_patch i18n_extension device_info_plus platform pasteboard]
- flutter_staggered_grid_view 0.6.2 [flutter]
- image_picker 0.8.6 [flutter image_picker_android image_picker_for_web image_picker_ios image_picker_platform_interface]
- jwt_decoder 2.0.1
- path_provider 2.0.11 [flutter path_provider_android path_provider_ios path_provider_linux path_provider_macos path_provider_platform_interface path_provider_windows]
- provider 6.0.4 [collection flutter nested]
- pull_to_refresh 2.0.0 [flutter]
- qr_code_scanner 1.0.1 [js flutter flutter_web_plugins]
- qr_flutter 4.0.0 [flutter qr]
- screenshot 1.2.3 [flutter]
- share_plus 6.3.0 [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]
- shared_preferences 2.0.15 [flutter shared_preferences_android shared_preferences_ios shared_preferences_linux shared_preferences_macos shared_preferences_platform_interface shared_preferences_web shared_preferences_windows]
- skeletons 0.0.3 [flutter]
- sumup 0.5.1 [flutter]
- table_calendar 3.0.8 [flutter intl simple_gesture_detector]
- toggle_switch 2.0.1 [flutter]
- url_launcher 6.1.6 [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 2.8.0 [flutter webview_flutter_android webview_flutter_platform_interface webview_flutter_wkwebview]

transitive dependencies:
- _fe_analyzer_shared 47.0.0 [meta]
- _flutterfire_internals 1.0.9 [cloud_firestore_platform_interface cloud_firestore_web collection firebase_core firebase_core_platform_interface flutter meta]
- amplify_analytics_pinpoint_android 0.6.10 [flutter]
- amplify_analytics_pinpoint_ios 0.6.10 [flutter]
- amplify_api_android 0.6.10 [flutter]
- amplify_api_ios 0.6.10 [amplify_core flutter]
- amplify_auth_cognito_android 0.6.10 [flutter]
- amplify_auth_cognito_ios 0.6.10 [amplify_core flutter]
- amplify_core 0.6.10 [aws_common collection flutter intl json_annotation meta plugin_platform_interface uuid]
- amplify_datastore_plugin_interface 0.6.10 [amplify_core collection flutter meta]
- amplify_flutter_android 0.6.10 [flutter]
- amplify_flutter_ios 0.6.10 [amplify_core flutter]
- amplify_storage_s3_android 0.6.10 [flutter]
- amplify_storage_s3_ios 0.6.10 [flutter]
- analyzer 4.7.0 [_fe_analyzer_shared collection convert crypto glob meta package_config path pub_semver source_span watcher yaml]
- archive 3.3.5 [crypto path pointycastle]
- args 2.3.1
- async 2.9.0 [collection meta]
- aws_common 0.1.1 [async collection http meta stream_transform uuid]
- boolean_selector 2.1.0 [source_span string_scanner]
- cached_network_image_platform_interface 2.0.0 [flutter flutter_cache_manager]
- cached_network_image_web 1.0.2 [flutter flutter_cache_manager cached_network_image_platform_interface]
- characters 1.2.1
- checked_yaml 2.0.1 [json_annotation source_span yaml]
- cli_util 0.3.5 [meta path]
- clock 1.1.1
- cloud_firestore_platform_interface 5.9.0 [_flutterfire_internals collection firebase_core flutter meta plugin_platform_interface]
- cloud_firestore_web 3.1.0 [_flutterfire_internals cloud_firestore_platform_interface collection firebase_core firebase_core_web flutter flutter_web_plugins js]
- collection 1.16.0
- convert 3.1.1 [typed_data]
- cross_file 0.3.3+2 [js meta]
- crypto 3.0.2 [typed_data]
- csslib 0.17.2 [source_span]
- device_info_plus 7.0.1 [device_info_plus_platform_interface ffi file flutter flutter_web_plugins meta win32]
- device_info_plus_platform_interface 6.0.1 [flutter meta plugin_platform_interface]
- diff_match_patch 0.4.1
- easy_logger 0.0.2 [flutter]
- equatable 2.0.5 [collection meta]
- fake_async 1.3.1 [clock collection]
- ffi 2.0.1
- file 6.1.4 [meta path]
- firebase_core_platform_interface 4.5.2 [collection flutter flutter_test meta plugin_platform_interface]
- firebase_core_web 2.0.1 [firebase_core_platform_interface flutter flutter_web_plugins js meta]
- firebase_messaging_platform_interface 4.2.7 [_flutterfire_internals firebase_core flutter meta plugin_platform_interface]
- firebase_messaging_web 3.2.7 [_flutterfire_internals firebase_core firebase_core_web firebase_messaging_platform_interface flutter flutter_web_plugins js meta]
- flutter_blurhash 0.7.0 [flutter]
- flutter_cache_manager 3.3.0 [clock collection file flutter http path path_provider pedantic rxdart sqflite uuid]
- flutter_colorpicker 1.0.3 [flutter]
- flutter_google_places_sdk_android 0.1.2+3 [flutter flutter_plugin_android_lifecycle flutter_google_places_sdk_platform_interface]
- flutter_google_places_sdk_ios 0.1.2+2 [flutter flutter_google_places_sdk_platform_interface]
- flutter_google_places_sdk_platform_interface 0.2.4+1 [flutter plugin_platform_interface]
- flutter_google_places_sdk_web 0.1.3+1 [flutter flutter_web_plugins flutter_google_places_sdk_platform_interface js google_maps collection]
- flutter_keyboard_visibility 5.4.0 [meta flutter_keyboard_visibility_platform_interface flutter_keyboard_visibility_linux flutter_keyboard_visibility_macos flutter_keyboard_visibility_web flutter_keyboard_visibility_windows flutter]
- flutter_keyboard_visibility_linux 1.0.0 [flutter_keyboard_visibility_platform_interface flutter]
- flutter_keyboard_visibility_macos 1.0.0 [flutter_keyboard_visibility_platform_interface flutter]
- flutter_keyboard_visibility_platform_interface 2.0.0 [flutter meta plugin_platform_interface]
- flutter_keyboard_visibility_web 2.0.0 [flutter_keyboard_visibility_platform_interface flutter_web_plugins flutter]
- flutter_keyboard_visibility_windows 1.0.0 [flutter_keyboard_visibility_platform_interface flutter]
- flutter_localizations 0.0.0 [flutter intl characters clock collection material_color_utilities meta path vector_math]
- flutter_plugin_android_lifecycle 2.0.7 [flutter]
- flutter_test 0.0.0 [flutter test_api path fake_async clock stack_trace vector_math async boolean_selector characters collection matcher material_color_utilities meta source_span stream_channel string_scanner term_glyph]
- flutter_web_plugins 0.0.0 [flutter js characters collection material_color_utilities meta vector_math]
- gettext_parser 0.2.0
- glob 2.1.0 [async collection file path string_scanner]
- google_maps 6.2.0 [js_wrapping meta]
- html 0.15.1 [csslib source_span]
- http 0.13.5 [async http_parser meta path]
- http_parser 4.0.2 [collection source_span string_scanner typed_data]
- i18n_extension 5.0.1 [sprintf args analyzer gettext_parser equatable intl flutter]
- image 3.2.2 [archive meta xml]
- image_picker_android 0.8.5+3 [flutter flutter_plugin_android_lifecycle image_picker_platform_interface]
- image_picker_for_web 2.1.10 [flutter flutter_web_plugins image_picker_platform_interface]
- image_picker_ios 0.8.6+1 [flutter image_picker_platform_interface]
- image_picker_platform_interface 2.6.2 [cross_file flutter http plugin_platform_interface]
- intl 0.17.0 [clock path]
- js 0.6.4
- js_wrapping 0.7.4 [js]
- json_annotation 4.7.0 [meta]
- matcher 0.12.12 [stack_trace]
- material_color_utilities 0.1.5
- meta 1.8.0
- mime 1.0.2
- nested 1.0.0 [flutter]
- octo_image 1.0.2 [flutter flutter_blurhash]
- package_config 2.1.0 [path]
- pasteboard 0.2.0 [flutter flutter_web_plugins js]
- path 1.8.2
- path_provider_android 2.0.21 [flutter path_provider_platform_interface]
- path_provider_ios 2.0.11 [flutter path_provider_platform_interface]
- path_provider_linux 2.1.7 [ffi flutter path path_provider_platform_interface xdg_directories]
- path_provider_macos 2.0.6 [flutter path_provider_platform_interface]
- path_provider_platform_interface 2.0.5 [flutter platform plugin_platform_interface]
- path_provider_windows 2.1.3 [ffi flutter path path_provider_platform_interface win32]
- pedantic 1.11.1
- petitparser 5.1.0 [meta]
- platform 3.1.0
- plugin_platform_interface 2.1.3 [meta]
- pointycastle 3.6.2 [collection convert js]
- process 4.2.4 [file path platform]
- pub_semver 2.1.2 [collection meta]
- qr 2.1.0 [meta]
- quiver 3.1.0 [matcher]
- rxdart 0.26.0
- share_plus_platform_interface 3.2.0 [cross_file flutter meta mime plugin_platform_interface path_provider uuid]
- shared_preferences_android 2.0.14 [flutter shared_preferences_platform_interface]
- shared_preferences_ios 2.1.1 [flutter shared_preferences_platform_interface]
- shared_preferences_linux 2.1.1 [file flutter path path_provider_linux path_provider_platform_interface shared_preferences_platform_interface]
- shared_preferences_macos 2.0.4 [flutter shared_preferences_platform_interface]
- shared_preferences_platform_interface 2.1.0 [flutter plugin_platform_interface]
- shared_preferences_web 2.0.4 [flutter flutter_web_plugins shared_preferences_platform_interface]
- shared_preferences_windows 2.1.1 [file flutter path path_provider_platform_interface path_provider_windows shared_preferences_platform_interface]
- simple_gesture_detector 0.2.0 [flutter]
- sky_engine 0.0.99
- source_span 1.9.0 [collection path term_glyph]
- sprintf 6.0.2
- sqflite 2.2.0+3 [flutter sqflite_common path]
- sqflite_common 2.4.0+2 [synchronized path meta]
- stack_trace 1.10.0 [path]
- stream_channel 2.1.0 [async]
- stream_transform 2.1.0
- string_scanner 1.1.1 [source_span]
- synchronized 3.0.0+3
- term_glyph 1.2.1
- test_api 0.4.12 [async boolean_selector collection meta source_span stack_trace stream_channel string_scanner term_glyph matcher]
- tuple 2.0.1
- typed_data 1.3.1 [collection]
- universal_io 2.0.4 [collection crypto meta typed_data]
- url_launcher_android 6.0.21 [flutter url_launcher_platform_interface]
- url_launcher_ios 6.0.17 [flutter url_launcher_platform_interface]
- url_launcher_linux 3.0.1 [flutter url_launcher_platform_interface]
- url_launcher_macos 3.0.1 [flutter url_launcher_platform_interface]
- url_launcher_platform_interface 2.1.1 [flutter plugin_platform_interface]
- url_launcher_web 2.0.13 [flutter flutter_web_plugins url_launcher_platform_interface]
- url_launcher_windows 3.0.1 [flutter url_launcher_platform_interface]
- uuid 3.0.6 [crypto]
- vector_math 2.1.2
- watcher 1.0.2 [async path]
- webview_flutter_android 2.10.4 [flutter webview_flutter_platform_interface]
- webview_flutter_platform_interface 1.9.5 [flutter meta plugin_platform_interface]
- webview_flutter_wkwebview 2.9.5 [flutter path webview_flutter_platform_interface]
- win32 3.1.1 [ffi]
- xdg_directories 0.2.0+2 [meta path process]
- xml 6.1.0 [collection meta petitparser]
- yaml 3.1.1 [collection source_span string_scanner]

Device

Iphone SE (3rd generation)

OS

IOS 16.0

Deployment Method

Amplify CLI

CLI Version

10.5.1

Additional Context

No response

Amplify Config

{ "UserAgent": "aws-amplify-cli/2.0", "Version": "1.0", "api": { "plugins": { "awsAPIPlugin": { "xxxapp": { "endpointType": "GraphQL", "endpoint": "https://XXX.appsync-api.eu-central-1.amazonaws.com/graphql", "region": "eu-central-1", "authorizationType": "AWS_IAM" }, "xxxrest": { "endpointType": "REST", "endpoint": "https://XXX.execute-api.eu-central-1.amazonaws.com/dev", "region": "eu-central-1", "authorizationType": "AWS_IAM" } } } }, "auth": { "plugins": { "awsCognitoAuthPlugin": { "UserAgent": "aws-amplify-cli/0.1.0", "Version": "0.1.0", "IdentityManager": { "Default": {} }, "CredentialsProvider": { "CognitoIdentity": { "Default": { "PoolId": "eu-central-1:xxx", "Region": "eu-central-1" } } }, "CognitoUserPool": { "Default": { "PoolId": "eu-central-1_xxx", "AppClientId": "xxxx", "Region": "eu-central-1" } }, "Auth": { "Default": { "OAuth": { "WebDomain": "xxxx-dev.auth.eu-central-1.amazoncognito.com", "AppClientId": "xxxx", "SignInRedirectURI": "xxx://", "SignOutRedirectURI": "xxx://", "Scopes": [ "phone", "email", "openid", "profile", "aws.cognito.signin.user.admin" ] }, "authenticationFlowType": "USER_SRP_AUTH", "socialProviders": [ "GOOGLE" ], "usernameAttributes": [ "EMAIL" ], "signupAttributes": [ "EMAIL", "NAME" ], "passwordProtectionSettings": { "passwordPolicyMinLength": 8, "passwordPolicyCharacters": [] }, "mfaConfiguration": "OPTIONAL", "mfaTypes": [ "TOTP" ], "verificationMechanisms": [ "EMAIL" ] } }, "AppSync": { "Default": { "ApiUrl": "https://xxxx.appsync-api.eu-central-1.amazonaws.com/graphql", "Region": "eu-central-1", "AuthMode": "AWS_IAM", "ClientDatabasePrefix": "xxx_AWS_IAM" }, "dolceparadisoapp_AMAZON_COGNITO_USER_POOLS": { "ApiUrl": "https://xxxx.appsync-api.eu-central-1.amazonaws.com/graphql", "Region": "eu-central-1", "AuthMode": "AMAZON_COGNITO_USER_POOLS", "ClientDatabasePrefix": "xxxx_AMAZON_COGNITO_USER_POOLS" } }, "S3TransferUtility": { "Default": { "Bucket": "xxxx-dev", "Region": "eu-central-1" } }, "DynamoDBObjectMapper": { "Default": { "Region": "eu-central-1" } }, "PinpointAnalytics": { "Default": { "AppId": "xxxx", "Region": "eu-central-1" } }, "PinpointTargeting": { "Default": { "Region": "eu-central-1" } } } } }, "storage": { "plugins": { "awsS3StoragePlugin": { "bucket": "xxxx-dev", "region": "eu-central-1", "defaultAccessLevel": "guest" }, "awsDynamoDbStoragePlugin": { "partitionKeyName": "id", "region": "eu-central-1", "arn": "arn:aws:dynamodb:eu-central-1:xxxxx:table/xxxx-dev", "streamArn": "arn:aws:dynamodb:eu-central-1:xxxxx:table/xxx-dev/stream/2022-12-01T09:24:25.413", "partitionKeyType": "S", "name": "xxxx-dev" } } }, "analytics": { "plugins": { "awsPinpointAnalyticsPlugin": { "pinpointAnalytics": { "appId": "xxxxx", "region": "eu-central-1" }, "pinpointTargeting": { "region": "eu-central-1" } } } } }

ghi8GPA commented 1 year ago

I have tried by switching the default auth type through amplify cli, and if I swap AWS_IAM as default with cognito, It seems that it is working for unauthenticated users BUT not working for privates, owners and groups.

{
  "version": 1,
  "serviceConfiguration": {
    "apiName": "XXX",
    "serviceName": "AppSync",
    "defaultAuthType": {
      "mode": "AWS_IAM"
    },
    "conflictResolution": {},
    "additionalAuthTypes": [
      {
        "mode": "AMAZON_COGNITO_USER_POOLS",
        "cognitoUserPoolId": "XXXX"
      }
    ]
  }
}
ragingsquirrel3 commented 1 year ago

Hey @ghi8GPA, sorry you are facing this issue. It looks like you are interacting with a backend that has multiple authorization modes and you are not specifying the auth mode via apiName parameter in your requests. The API category does not do anything fancy to try to figure out the auth mode, just uses default mode unless specified.

Have you tried going through instructions on https://docs.amplify.aws/lib/graphqlapi/authz/q/platform/flutter/#configure-multiple-authorization-modes and seeing if it helps?

Also note that in dev preview this is a little easier bc you can specify the authorizationMode parameter in a GraphQLRequest or a model helper. In stable, however, you have to use apiName and have expected entries in your amplify configuration file.

ghi8GPA commented 1 year ago

Hi @ragingsquirrel3, Thanks for the fast reply.

 var result = await Amplify.API.query(request: ModelQueries.get(
        apiName: 'XXX',
        DPSettings.classType, 'CHECKOUT_MODES',
        authorizationMode: auth == true ? APIAuthorizationType.userPools : APIAuthorizationType.iam
        )).response;

I managed to let this works, by setting apiName. It also works on dev preview (I'm using 1.0.0-next.1), but I still require apiName, authorizationMode alone is not enough.

The point is that, even if I have two authorizationModes, I still have only one apiname that in this case it's the same on iam and cognito.

Hope that this could be fixed in the future, meanwhile I can create a service that checks if the user is authenticated and add the name of the api.

Thanks

ragingsquirrel3 commented 1 year ago

I'm glad you got this working but requiring apiName in dev preview is not expected (assuming the amplifyconfiguration.dart file doesn't have modifications left from making it work in stable) so I want to ask some more questions to verify.

Yes, I understand there is only 1 apiName, but using this in stable is a workaround needed bc of lack of authorizationMode parameter in underlying android/ios libraries (I agree it's annoying in this use case).

When you test w dev preview and state that apiName is required, does your amplifyconfiguration file have only 1 GraphQL entry like configuration you attached to file the issue? If so, apiName should not be required in dev preview and only authorizationMode should work. I was wondering if you had created another entry to get it working with stable (which is required) and did not remove to try w dev preview. If there are multiple GraphQL entries, then apiName is required to disambiguate. In dev preview, if you delete the configuration file locally and run amplify pull I would not expect apiName to be required. If apiName is required when there is only 1 entry in dev preview, do you get an error? Or do you just not have expected authorization logic occur at runtime?

Thanks for the detail and again for filing this issue.

ghi8GPA commented 1 year ago

Hello, this is the following configuration:

const amplifyconfig = ''' {
    "UserAgent": "aws-amplify-cli/2.0",
    "Version": "1.0",
    "api": {
        "plugins": {
            "awsAPIPlugin": {
                "XXX": {
                    "endpointType": "GraphQL",
                    "endpoint": "https://XXX.appsync-api.XXX.amazonaws.com/graphql",
                    "region": "XXX",
                    "authorizationType": "AMAZON_COGNITO_USER_POOLS"
                },
                "automatorest": {
                    "endpointType": "REST",
                    "endpoint": "https://XXX.execute-api.XXX.amazonaws.com/dev",
                    "region": "XXX",
                    "authorizationType": "AWS_IAM"
                }
            }
        }
    },
    "auth": {
        "plugins": {
            "awsCognitoAuthPlugin": {
                "UserAgent": "aws-amplify-cli/0.1.0",
                "Version": "0.1.0",
                "IdentityManager": {
                    "Default": {}
                },
                "CredentialsProvider": {
                    "CognitoIdentity": {
                        "Default": {
                            "PoolId": "XXX:XXX",
                            "Region": "XXX"
                        }
                    }
                },
                "CognitoUserPool": {
                    "Default": {
                        "PoolId": "XXX",
                        "AppClientId": "XXX",
                        "Region": "XXX"
                    }
                },
                "Auth": {
                    "Default": {
                        "OAuth": {
                            "WebDomain": "XXX.auth.XXX.amazoncognito.com",
                            "AppClientId": "XXX",
                            "SignInRedirectURI": "XXX://",
                            "SignOutRedirectURI": "XXX://",
                            "Scopes": [
                                "phone",
                                "email",
                                "openid",
                                "profile",
                                "aws.cognito.signin.user.admin"
                            ]
                        },
                        "authenticationFlowType": "USER_SRP_AUTH",
                        "socialProviders": [
                            "GOOGLE",
                            "APPLE"
                        ],
                        "usernameAttributes": [
                            "EMAIL"
                        ],
                        "signupAttributes": [
                            "EMAIL"
                        ],
                        "passwordProtectionSettings": {
                            "passwordPolicyMinLength": 8,
                            "passwordPolicyCharacters": []
                        },
                        "mfaConfiguration": "OFF",
                        "mfaTypes": [
                            "SMS"
                        ],
                        "verificationMechanisms": [
                            "EMAIL"
                        ]
                    }
                },
                "AppSync": {
                    "Default": {
                        "ApiUrl": "https://XXX.appsync-api.XXX.amazonaws.com/graphql",
                        "Region": "XXX",
                        "AuthMode": "AMAZON_COGNITO_USER_POOLS",
                        "ClientDatabasePrefix": "XXX_AMAZON_COGNITO_USER_POOLS"
                    },
                    "XXX_AWS_IAM": {
                        "ApiUrl": "https://XXX.appsync-api.XXX.amazonaws.com/graphql",
                        "Region": "XXX",
                        "AuthMode": "AWS_IAM",
                        "ClientDatabasePrefix": "XXX_AWS_IAM"
                    }
                },
                "DynamoDBObjectMapper": {
                    "Default": {
                        "Region": "XXX"
                    }
                },
                "S3TransferUtility": {
                    "Default": {
                        "Bucket": "XXX-dev",
                        "Region": "XXX"
                    }
                }
            }
        }
    },
    "storage": {
        "plugins": {
            "awsDynamoDbStoragePlugin": {
                "partitionKeyName": "id",
                "region": "XXX",
                "arn": "arn:aws:dynamodb:XXX:XXX:table/ASecrets-dev",
                "streamArn": "arn:aws:dynamodb:XXX:XXX:table/XXX-dev/stream/2022-12-19T09:55:39.111",
                "partitionKeyType": "S",
                "name": "xxx-dev"
            },
            "awsS3StoragePlugin": {
                "bucket": "XXX-dev",
                "region": "XXX",
                "defaultAccessLevel": "guest"
            }
        }
    }
}''';

I need to add with another problem with the dev preview version: oath cognito users (google and Facebook) are considered unauthenticated users when calling an api gateway with a lambda attached. Is there a work around for this problem? on stable version is working correctly

ragingsquirrel3 commented 1 year ago

I will look into the API gateway issue, thanks for reporting.

ghi8GPA commented 1 year ago

The problem with API gateway is that as it use IAMROLE, the autogenerated groups for oauth2 social (in this example Goggle and Apple, the role names are {region}{userpoolId}_Google) don't have the associated default IAM role (authenticated role) and those groups are not recognised by the Amplify CLI, and so I cannot give them permission on the api gateway.

A workaround that I am trying is refactoring the lambda and using appsync instead of api gateway so that I can use cognito user pools.

this is what I am actually using for calling a lambda with appsync so that I can access them with a private /owner even with google/apple:

type Query {
  test(testInput: String!): String @function(name: "lambdaname-${env}") @auth(rules: [
    {allow: private, provider: userPools},
    {allow: groups, groups: ["group1", "group2"], provider: userPools}
  ]) 
}

ps. as codegen in flutter works only for models, I won't be able to have a generated query for this functions, so I need to parse the json response and map in manually.

Jordan-Nelson commented 1 year ago

Hi @ghi8GPA - Apologies for the delayed response. It sounds like you were able to resolve the original issue, but may have run into a secondary issue. If that is the case, I think it would make sense to capture those details in a new issue. Please let use know if you are still facing an issue.

Jordan-Nelson commented 1 year ago

@ghi8GPA - I am going to close this out. If you are facing a follow up issue, can you please open a new GitHub issue so that we can properly capture that? Thanks.