Flutter Amplify Cognito, no tokens using fetchAuthSession

2.7k Views Asked by At

I'm trying to implement authentication in my Flutter app using Cognito. I'm authenticating against an existing userPool which I've been successfully using for the past year in my React app.

However, with Flutter I'm not able to fetch the user's session. I'm able to login successfully but I'm unable to get any tokens using the fetchAuthSession() method. Any idea why this is happening? Here is some of my working and non-working code:

This code is successful...

Future _usersEmail() async {
    try {
      var attributes = (await Amplify.Auth.fetchUserAttributes()).toList();
      for (var attribute in attributes) {
        if (attribute.userAttributeKey == 'email') {
          print("user's email is ${attribute.value}");
          return '${attribute.value}';
        }
      }
      return 'no email';
    } on AuthException catch (e) {
      return '${e.message}';
    }
  }

This code is successful too...

  Future<bool> _isSignedIn() async {
    final CognitoAuthSession session =
        await Amplify.Auth.fetchAuthSession() as CognitoAuthSession;
    print('_isSignedIn: ${session.isSignedIn}');
    return session.isSignedIn;
  }

This code return null...

  Future _getIdToken() async {
    final CognitoAuthSession session =
        await Amplify.Auth.fetchAuthSession() as CognitoAuthSession;
    final idToken = session.userPoolTokens?.idToken;
    print('idToken: $idToken');
    return idToken;
  }

Here is my amplifyconfig...

{
  "UserAgent": "aws-amplify-cli/2.0",
  "Version": "1.0",
  "auth": {
      "plugins": {
          "awsCognitoAuthPlugin": {
              "UserAgent": "aws-amplify-cli/0.1.0",
              "Version": "0.1.0",
              "IdentityManager": {
                  "Default": {}
              },
              "CredentialsProvider": {
                  "CognitoIdentity": {
                      "Default": {
                          "PoolId": "us-east-1_abcxyz",
                          "Region": "us-east-1"
                      }
                  }
              },
              "CognitoUserPool": {
                  "Default": {
                      "PoolId": "us-east-1_abcxyz",
                      "AppClientId": "5j0kii90dJ09est43xh3X21",
                      "Region": "us-east-1"
                  }
              },
              "Auth": {
                  "Default": {
                      "authenticationFlowType": "USER_SRP_AUTH"
                  }
              }
          }
      }
  }
}
1

There are 1 best solutions below

1
On

you might need to set getAWSCredentials to true in your options parameter like so:

   final authSession = (await Amplify.Auth.fetchAuthSession(
      options: CognitoSessionOptions(getAWSCredentials: true),
    )) as CognitoAuthSession;