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

Amplify.configure() incorrectly throws JSON parsing validation error on valid JSON string. Improve error login on Amplify.configure() #4996

Closed
2 of 14 tasks
sisygoboom opened this issue Jun 9, 2024 · 4 comments
Labels
auth Issues related to the Auth Category bug Something is not working; the issue has reproducible steps and has been reproduced duplicate This issue or pull request already exists

Comments

@sisygoboom
Copy link

Description

I'm getting a json validation error on valid json in the amplifyconfiguration.dart file while calling Amplify.configure(). For what its worth, I tested with and without plugins and got the same error.

Error log:

Installing build\app\outputs\flutter-apk\app-debug.apk...        2,990ms
E/flutter ( 4331): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: ConfigurationError {
E/flutter ( 4331):   "message": "The provided configuration is not a valid json. Check underlyingException.",
E/flutter ( 4331):   "recoverySuggestion": "Inspect your amplifyconfiguration.dart and ensure that the string is proper json"
E/flutter ( 4331): }
E/flutter ( 4331): #0      AmplifyClass.configure (package:amplify_core/src/amplify_class.dart:121:9)
E/flutter ( 4331): #1      _configureAmplify (package:datingapp/main.dart:40:19)
E/flutter ( 4331): <asynchronous suspension>
E/flutter ( 4331): #2      main (package:datingapp/main.dart:23:5)
E/flutter ( 4331): <asynchronous suspension>
E/flutter ( 4331):
E/flutter ( 4331): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: ConfigurationError {
E/flutter ( 4331):   "message": "The provided configuration is not a valid json. Check underlyingException.",
E/flutter ( 4331):   "recoverySuggestion": "Inspect your amplifyconfiguration.dart and ensure that the string is proper json"
E/flutter ( 4331): }
E/flutter ( 4331): #0      AmplifyClass.configure (package:amplify_core/src/amplify_class.dart:121:9)
E/flutter ( 4331): #1      _configureAmplify (package:datingapp/main.dart:40:19)
E/flutter ( 4331): <asynchronous suspension>
E/flutter ( 4331): #2      main (package:datingapp/main.dart:23:5)
E/flutter ( 4331): <asynchronous suspension>
E/flutter ( 4331):
Syncing files to device sdk gphone64 x86 64...                     243ms

apmlifyconfiguration.dart

const amplifyConfig = '''{
  "UserAgent": "@aws-amplify/client-config/1.0.4",
  "Version": "1.0",
  "auth": {
    "plugins": {
      "awsCognitoAuthPlugin": {
        "UserAgent": "@aws-amplify/client-config/1.0.4",
        "Version": "1.0",
        "CognitoUserPool": {
          "Default": {
            "PoolId": "[REDACTED]",
            "AppClientId": "[REDACTED]",
            "Region": "eu-west-2"
          }
        },
        "CredentialsProvider": {
          "CognitoIdentity": {
            "Default": {
              "PoolId": "[REDACTED]",
              "Region": "eu-west-2"
            }
          }
        },
        "Auth": {
          "Default": {
            "authenticationFlowType": "USER_SRP_AUTH",
            "mfaConfiguration": "OFF",
            "mfaTypes": [],
            "passwordProtectionSettings": {
              "passwordPolicyMinLength": 8,
              "passwordPolicyCharacters": [
                "REQUIRES_NUMBERS",
                "REQUIRES_LOWERCASE",
                "REQUIRES_UPPERCASE",
                "REQUIRES_SYMBOLS"
              ]
            },
            "signupAttributes": [
              "PHONE_NUMBER"
            ],
            "usernameAttributes": [
              "PHONE_NUMBER"
            ],
            "verificationMechanisms": [
              "PHONE_NUMBER"
            ],
            "OAuth": {
              "WebDomain": "[REDACTED]",
              "Scopes": [
                "phone",
                "email",
                "openid",
                "profile",
                "aws.cognito.signin.user.admin"
              ],
              "SignInRedirectURI": "paritae://callback",
              "SignOutRedirectURI": "paritae://logout"
            }
          }
        },
        "AppSync": {
          "Default": {
            "ApiUrl": "[REDACTED]",
            "Region": "eu-west-2",
            "AuthMode": "AWS_IAM",
            "ClientDatabasePrefix": "data_AWS_IAM"
          },
          "data_AMAZON_COGNITO_USER_POOLS": {
            "ApiUrl": "[REDACTED]",
            "Region": "eu-west-2",
            "AuthMode": "AMAZON_COGNITO_USER_POOLS",
            "ClientDatabasePrefix": "data_AMAZON_COGNITO_USER_POOLS"
          }
        }
      }
    }
  },
  "api": {
    "plugins": {
      "awsAPIPlugin": {
        "data": {
          "endpointType": "GraphQL",
          "endpoint": "[REDACTED]",
          "region": "eu-west-2",
          "authorizationType": "AWS_IAM"
        }
      }
    }
  }
}''';

main.dart:

import 'package:amplify_auth_cognito/amplify_auth_cognito.dart';
import 'package:amplify_authenticator/amplify_authenticator.dart';
import 'package:amplify_flutter/amplify_flutter.dart';
import 'package:datingapp/Theme/nativeTheme.dart';
import 'package:datingapp/l10n/l10n.dart';
import 'package:datingapp/models/businessLayer/global.dart' as g;
import 'package:datingapp/provider/local_provider.dart';
import 'package:datingapp/screens/splashScreen.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:flutter_phoenix/flutter_phoenix.dart';
import 'package:flutter_gen/gen_l10n/app_localizations.dart';
import 'package:amplify_api/amplify_api.dart';

import 'amplifyconfiguration.dart';
import 'models/ModelProvider.dart';

Future<void> main() async {
  try {
    WidgetsFlutterBinding.ensureInitialized();
    await _configureAmplify();
    runApp(Phoenix(child: MyApp()));
    SystemChrome.setEnabledSystemUIMode(
      SystemUiMode.edgeToEdge,
      overlays: SystemUiOverlay.values,
    );
  } on AmplifyException catch (e) {
    runApp(Text("Error configuring Amplify: ${e.message}"));
  }
}

Future<void> _configureAmplify() async {
  try {
    final api = AmplifyAPI(
        options: APIPluginOptions(modelProvider: ModelProvider.instance));
    final auth = AmplifyAuthCognito();
    await Amplify.addPlugins([auth, api]);
    await Amplify.configure(amplifyConfig);
    safePrint('Successfully configured');
  } on Exception catch (e) {
    safePrint('Error configuring Amplify: $e');
  }
}

class MyApp extends StatefulWidget {
  @override
  MyAppState createState() => new MyAppState();
}

class MyAppState extends State<MyApp> {
  dynamic analytics;
  dynamic observer;

  @override
  void initState() {
    super.initState();
    //_configureAmplify();
    //_init();
  }

  // Future () async {
  //   try {
  //     var brightness = SchedulerBinding.instance.window.platformBrightness;
  //     print("HEllo main");
  //     bool isDarkMode = brightness == Brightness.dark;
  //     g.isDarkModeEnable = isDarkMode;
  //   } catch (e) {
  //     print('Exception - base.dart - (): ' + e.toString());
  //   }
  // }

  // _init() async {
  //   try {
  //     SharedPreferences sp = await SharedPreferences.getInstance();
  //     if (sp.containsKey('isDarkMode') && sp.getBool('isDarkMode') != null) {
  //       g.isDarkModeEnable = sp.getBool('isDarkMode');
  //     } else {
  //       g.isDarkModeEnable = false;
  //     }
  //   } catch (e) {
  //     print('Exception - main.dart - _init(): ' + e.toString());
  //   }
  // }

  @override
  Widget build(BuildContext context) {
    return Authenticator(
        // authenticatorBuilder: (BuildContext context, AuthenticatorState state) {
        //   return SocialLoginButtons();
        // },
        child: BlocProvider(
      create: (context) => LocaleCubit(),
      child: BlocBuilder<LocaleCubit, Locale?>(
        builder: (context, locale) {
          return MaterialApp(
            //builder: Authenticator.builder(),
            debugShowCheckedModeBanner: false,
            theme: nativeTheme(g.isDarkModeEnable),
            home: SplashScreen(a: analytics, o: observer),
            locale: locale,
            supportedLocales: L10n.all,
            localizationsDelegates: [
              AppLocalizations.delegate,
              GlobalMaterialLocalizations.delegate,
              GlobalCupertinoLocalizations.delegate,
              GlobalWidgetsLocalizations.delegate,
            ],
          );
        },
      ),
    ));
  }
}

Categories

  • Analytics
  • API (REST)
  • API (GraphQL)
  • Auth
  • Authenticator
  • DataStore
  • Notifications (Push)
  • Storage

Steps to Reproduce

  1. Copy the configuration
  2. have a main file that looks like the one supplied
  3. flutter run

Screenshots

No response

Platforms

  • iOS
  • Android
  • Web
  • macOS
  • Windows
  • Linux

Flutter Version

3.22.1

Amplify Flutter Version

2.1.0

Deployment Method

AWS CDK

Schema

No response

@printSamuel
Copy link

printSamuel commented Jun 9, 2024

Hey @sisygoboom,

there are two types of Amplify configuration files... I encountered the same issue while working with Amplify Gen2 and flutter. What helped me was adding:
--outputs-version 0
to my create command.

Complete Command:
npx ampx sandbox --outputs-format dart --outputs-out-dir lib --outputs-version 0

Source:

when using Amplify Gen 2 with Flutter, you must downgrade the generated client configuration file (amplify_outputs.dart) with [--outputs-version 0]

Hope that helps. :-)

@sisygoboom
Copy link
Author

sisygoboom commented Jun 9, 2024

Hi @printSamuel, I have been using that command for weeks now and it worked fine until recently. not using --outputs-version 0 creates a completely different file named amplify_output.dart rather than apmlifyconfiguration.dart

@sisygoboom sisygoboom changed the title Amplify.configure() incorrectly throws JSON parsing validation error on valid JSON string Amplify.configure() incorrectly throws JSON parsing validation error on valid JSON string. Improve error login on Amplify.configure() Jun 9, 2024
@NikaHsn
Copy link
Contributor

NikaHsn commented Jun 10, 2024

@sisygoboom Sorry that you are facing this issue. We will look into this and get back to you when we have updates.

@NikaHsn NikaHsn added bug Something is not working; the issue has reproducible steps and has been reproduced duplicate This issue or pull request already exists auth Issues related to the Auth Category labels Jun 10, 2024
@NikaHsn
Copy link
Contributor

NikaHsn commented Jun 10, 2024

Based on the provided amplifyconfiguration.dart the "OAuth" configuration is missing the "AppClientId" which is a required field. there is an open issue for this aws-amplify/amplify-backend#1551
We also have an open issue for improving error messages of Amplify.configure() API #4922 so I marked this issue as duplicate of #4922
thanks for opening this issue and please feel free to open a new issue if you faced any other problem.

@NikaHsn NikaHsn closed this as completed Jun 10, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
auth Issues related to the Auth Category bug Something is not working; the issue has reproducible steps and has been reproduced duplicate This issue or pull request already exists
Projects
None yet
Development

No branches or pull requests

3 participants