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

Users getting session expired right after sign in #1271

Closed
brunovsiqueira opened this issue Jan 14, 2022 · 79 comments
Closed

Users getting session expired right after sign in #1271

brunovsiqueira opened this issue Jan 14, 2022 · 79 comments
Assignees
Labels
auth Issues related to the Auth Category bug Something is not working; the issue has reproducible steps and has been reproduced fixed-in-release-candidate Issues that have been addressed in the current release-candidate branch pending-close-response-required The issue will be closed if details necessary to reproduce the issue are not provided within 7 days.

Comments

@brunovsiqueira
Copy link

brunovsiqueira commented Jan 14, 2022

Hi there.

We have two android users in production which are not being able to use our app because Amplify returns session expired right after signIn when we call fetchAuthSession.

Inspecting this user's logs, what I see is the following:

1- We check user session by calling (Amplify.Auth.getCurrentUser(), Amplify.Auth.fetchAuthSession) when the app is opened. We consider session expired if InvalidStateException or SessionExpiredException is thrown and then we call Amplify.Auth.signOut() if session has expired. In the mentioned case, this user session is considered expired and he is logged out.

2- After that, the user called signIn successfully and "isSignedIn" flag returned true.

3- Right after signIn (sequentially), Amplify.Auth.fetchAuthSession is called in order to get user token (JWT) to call one of our APIs. When fetchAuthSession is called, this is the result according to the logs:
(message: Your session has expired., recoverySuggestion: Please sign in and reattempt the operation., underlyingException: null)
Because user session has expired right after signIn, the user is not able to get the token and consequently is not able to consume none of our APIs.

This behavior is completely weird since the user has just logged in and is getting session expired. I was not able to reproduce it.

Since we have production users facing this problem, can anyone please help me understand/solve the problem?

@brunovsiqueira brunovsiqueira changed the title Users gettings session expired right after sign in Users getting session expired right after sign in Jan 14, 2022
@brunovsiqueira
Copy link
Author

@haverchuck @Amplifiyer

@fjnoyp
Copy link
Contributor

fjnoyp commented Jan 18, 2022

Hi @brunovsiqueira

Have some followup questions to better help you here:

  1. Is this Android only or also on iOS?

  2. Are you able to reproduce this on your side when deploying your app to an Android device or emulator?

  3. Which Amplify CLI version are you using?

  4. We have a similar issue, it's a bit long and we're still working on resolution on it. For them, calling await getCurrentUser() right after await signIn() throws a SignedOutException - can you verify if you have the same behavior?

@fjnoyp fjnoyp self-assigned this Jan 18, 2022
@brunovsiqueira
Copy link
Author

brunovsiqueira commented Jan 18, 2022

Hi @fjnoyp

  1. Only android AFAIK. In my app logs I only see this problem for Android devices.
  2. No, I wasn't.
  3. Amplify config:
String 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": {}
                },
                "CognitoUserPool": {
                    "Default": {
                        "PoolId": "${getPoolIdForEnv()}",
                        "AppClientId": "${getAppClientIdForEnv()}",
                        "Region": "${getRegionForEnv()}"
                    }
                },
                "Auth": {
                    "Default": {
                        "authenticationFlowType": "USER_SRP_AUTH"
                    }
                }
               
            }
        }
    }
}''';
  1. I tested here and the answer is no. getCurrentUser right after signIn works properly.

Also, my amplify versions:

amplify_auth_cognito: 0.2.10
amplify_core: 0.2.10
amplify_flutter: 0.2.10

@haverchuck
Copy link
Member

@brunovsiqueira Do you know which devices these are occurring on?

@brunovsiqueira
Copy link
Author

brunovsiqueira commented Jan 18, 2022

@haverchuck Samsung SM-G973F (Galaxy S10), SM-N770F (Galaxy Note 10 lite).

Just letting you guys know, the same user who had this problem on SM-N770F (Galaxy Note 10 lite) tested on SM-N950F (Galaxy Note 20 FE) and it worked. So it seems to be linked with Samsung devices (?).

Additionaly, a user who had the same problem but only reinstalled the app, continue having the problem.

@offlineprogrammer offlineprogrammer added the auth Issues related to the Auth Category label Jan 19, 2022
@dnys1
Copy link
Contributor

dnys1 commented Jan 19, 2022

Could this explain the behavior you're seeing?

aws-amplify/amplify-android#1485 (comment)

@brunovsiqueira
Copy link
Author

Hi @dnys1.

One of our users who reported the problem reinstalled the app from scratch. The behavior that we see in our logs is even stranger:

1- Because he reinstalled the App, he had no session so no SessionExpired was thrown.
2- He tried to sign in (in theory by the first time, since he reinstalled the app) and he signedIn with "success" (which is confirmed if we look at cognito console). By success I mean no exception was thrown when calling the signIn method.
Screen Shot 2022-01-19 at 18 54 52
3- Right after signIn we call fetchAuthSession to get JWT token and it throw SessionExpiredException.

One thing that may be linked to the issue you mentioned is the fact that no exception is thrown when we call signIn, but instead it is thrown we try to fetch user session by calling fetchAuthSession (not sure if this behavior is expected, maybe yes).

I don't think the issue you mentioned explains our problem, since even reinstalling the app the user gets SessionExpired when fetching session right after a "successful" sign in.

@dnys1
Copy link
Contributor

dnys1 commented Jan 20, 2022

Hmm okay, I will look into it more tomorrow. Does the object returned from the signIn call provide any info?

I did try to reproduce this both in an emulator (Pixel) and a physical device (Galaxy S8) and for after the access token expired and after the access & refresh tokens expired. For all cases, I got the expected behavior. Unfortunately, I'm not sure what else to test for this.. these kinds of bugs are obviously very difficult to triage.

@brunovsiqueira
Copy link
Author

Actually I don't have access to the signIn object in my logs.

I think I am going to try to create an emulador which has same configurations of the mentioned devices (S10 and Note 10). I agree this bugs are very hard to reproduce.

@brunovsiqueira
Copy link
Author

@dnys1 were you able to figure something out?

@fjnoyp fjnoyp removed their assignment Jan 20, 2022
@dnys1
Copy link
Contributor

dnys1 commented Jan 20, 2022

Unfortunately, I haven't made any more progress @brunovsiqueira - I'm at a bit of a loss. Would you be willing to open a ticket with the amplify-android team with the same information? It's possible they may have some more insight as to what could be happening.

@bwhiteTP
Copy link

We are having this problem as well.

@brunovsiqueira
Copy link
Author

@dnys1 yes, I can. But it is happening in the flutter plugin.

@fjnoyp
Copy link
Contributor

fjnoyp commented Jan 24, 2022

Indeed. The Amplify Flutter plug-in's functionality is built on top of Amplify Android which might be the root source of the problem. Just to confirm, the issue you encounter does not happen on iOS?

@brunovsiqueira
Copy link
Author

brunovsiqueira commented Jan 24, 2022

@fjnoyp I haven't seen any of this issue' logs on iOS, so I assume it is not happening on iOS but I am not totally sure.

@brunovsiqueira
Copy link
Author

We are having this problem as well.

@bwhiteTP is this problem happening for you only on Android as well? Do you have any information about the devices where it is happening?

@bwhiteTP
Copy link

bwhiteTP commented Jan 24, 2022

This does not happen to us on iOS, only Android. It also only seems to happen with sign in with email. It does't happen on sign up and it doesn't happen every time.
The way I've reproduced it:

  1. Sign in with SSO
  2. Intentionally Sign out
  3. Sign up with email
  4. Intentionally Sign out
  5. Sign in with email - Get signed out immediately

After I sign in with email and getting signed out a few more times it will just start working randomly. So the issue seems to fix itself after several tries.

@brunovsiqueira
Copy link
Author

We don't use SSO and we only sign in our user using "username", not email.

@bwhiteTP do you know in which device the error is happening?

@brunovsiqueira
Copy link
Author

Complete logs:

SessionExpiredException(message: Your session has expired., recoverySuggestion: Please sign in and reattempt the operation., underlyingException: null)
#0      AmplifyAuthCognitoMethodChannel.fetchAuthSession (package:amplify_auth_cognito\/method_channel_auth_cognito.dart:246)
<asynchronous suspension>
#1      AmplifyAuthCognito.fetchAuthSession (package:amplify_auth_cognito\/amplify_auth_cognito.dart:121)
<asynchronous suspension>
#2      SessionService._fetchSession (package:btg_auth_core\/src\/services\/session_service.dart:23)
<asynchronous suspension>
#3      SessionService.getAccessJWTToken (package:btg_auth_core\/src\/services\/session_service.dart:34)
<asynchronous suspension>
#4      BasicAPI.getHeaders (package:btg_auth_core\/src\/services\/api\/basic_api.dart:27)
<asynchronous suspension>
#5      BasicAPI.httpGet (package:btg_auth_core\/src\/services\/api\/basic_api.dart:136)
<asynchronous suspension>
#6      GkRemoteDatasourceImpl.getSelfUser (package:btg_auth_core\/src\/datasources\/gk_remote_datasource.dart:23)
<asynchronous suspension>
#7      UserServiceImpl.getSelfUser (package:btg_auth_core\/src\/services\/user_service_impl.dart:28)
<asynchronous suspension>
#8      UserViewModel.fetchCurrentUserData (package:btg_auth_core\/src\/viewmodels\/user_viewmodel.dart:33)
<asynchronous suspension>
#9      LoginViewModel.login (package:btg_login\/src\/viewmodels\/login_viewmodel.dart:218)
<asynchronous suspension>
#10     _LoginPasswordPageState.build.<anonymous closure> (package:btg_login\/src\/pages\/login_password_page.dart:72)
<asynchronous suspension>

@fjnoyp
Copy link
Contributor

fjnoyp commented Jan 24, 2022

Hi @brunovsiqueira @bwhiteTP thanks for sharing that information. Based on the information you've shared this sounds like an issue that is coming from the underlying Amplify Android library.

Can you do what @dnys1 suggested and create an issue on the Amplify Android git repo?

https://github.com/aws-amplify/amplify-android/issues

@fjnoyp fjnoyp added the Android Issues specific to the Android Platform label Jan 24, 2022
@brunovsiqueira
Copy link
Author

I have created the issue on the Amplify Android git repo: aws-amplify/amplify-android#1635.

@fjnoyp
Copy link
Contributor

fjnoyp commented Jan 24, 2022

Great thank you. We can monitor from there.

@brunovsiqueira
Copy link
Author

Hi @Jordan-Nelson. Thanks for the update. Looking forward to hear back from you.

@gopbarbosa
Copy link

I hope this message finds you well. I wanted to address the issue reported by @brunovsiqueira . I recently updated the library to version 1.10.0, but some users are still experiencing the same problem. Unfortunately, I don't have enough data at the moment to determine if the error rate has increased or decreased. I am actively seeking additional solutions and will continue to closely monitor the situation.

Thank you for your understanding, and any further feedback would be greatly appreciated.

@Jordan-Nelson
Copy link
Member

@GarbielBarbosa thanks for letting us know. If you are able to get enough info to reproduce this issue, please let us know so that we can investigate further. If there is any info you can provide (devices, OSs, stack traces, etc.) that you think might help, please do provide it.

@Jordan-Nelson
Copy link
Member

@GarbielBarbosa Just to confirm, did you mean version 1.1.0?

@gopbarbosa
Copy link

@Jordan-Nelson, I apologize for the mistake. I am using version 1.1.0 of the library.
I am unable to reproduce the error on my devices; the errors are only reported by my users. Additionally, I am able to track them through Crashlytics/Firebase.
Below is the structure of my code.

Future<void> hasUser() async {
    final ILocalStorage storage = Modular.get();
    final User? user = await storage.getUser();
  
      // verifica se o usuário está logado.
      try {
        await Amplify.Auth.getCurrentUser();
      } catch (e) {
        showAlertErrorLogin(code: '1000');
        await goToLogin();
        return;
      }

      // Retorna os tokens do cognito e os fixa no usuário
      try {
        final session = await Amplify.Auth.getPlugin(
          AmplifyAuthCognito.pluginKey,
        ).fetchAuthSession();
        if (session.isSignedIn) {
          storage.user.acessToken = session.userPoolTokensResult.value.accessToken.toJson();
          storage.user.idToken = session.userPoolTokensResult.value.idToken.toJson();
          storage.user.refreshToken = session.userPoolTokensResult.value.refreshToken;
        }
      } catch (e, stackTrace) {
        await FirebaseCrashlytics.instance.recordError(e, stackTrace, reason: 'Erro ao logar fetchAuthSession');
        AnalyticsFunctions.saveLog('Erro ao logar fetchAuthSession', {'error': e.toString()});
        try {
          final session = await Amplify.Auth.getPlugin(
            AmplifyAuthCognito.pluginKey,
          ).fetchAuthSession();
          if (session.isSignedIn) {
            storage.user.acessToken = session.userPoolTokensResult.value.accessToken.toJson();
            storage.user.idToken = session.userPoolTokensResult.value.idToken.toJson();
            storage.user.refreshToken = session.userPoolTokensResult.value.refreshToken;
          }
        } catch (e) {
          await FirebaseCrashlytics.instance.recordError(e, stackTrace, reason: 'Erro ao logar fetchAuthSession 2');
          AnalyticsFunctions.saveLog('Erro ao logar fetchAuthSession', {'error': e.toString()});
          showAlertErrorLogin(code: '1002');
          await goToLogin();
          return;
        }
      }

      // Caso o id token do usuário ou o email esteja vazio o usuário é deslogado.
      if (storage.user.idToken == null || storage.user.email == null) {
        await Amplify.Auth.signOut(
          options: const SignOutOptions(),
        );
        showAlertErrorLogin(code: '1003');
        await goToLogin();
        return;
      }

      await goToHome();
    }
  }

Would this type of StackTrace be useful?

Captura de Tela 2023-05-27 às 17 19 15

@Jordan-Nelson
Copy link
Member

@GarbielBarbosa The stack trace indicates the error is coming from the method channel implementation of fetchAuthSession. Version 0.x of Amplify wraps Amplify iOS and Android using method channels. This implementation is no longer present in version 1.x of Amplify is it has been re-written in Dart. Is it possible that the users that are experiencing this are using a version of your app that still uses version 0.x of Amplify?

@gopbarbosa
Copy link

Hi, @Jordan-Nelson! I'd like to confirm if the correct method to obtain the tokens is as follows:

  final session = await Amplify.Auth.getPlugin(
      AmplifyAuthCognito.pluginKey,
    ).fetchAuthSession();
    if (session.isSignedIn) {
      storage.user.acessToken = session.userPoolTokensResult.value.accessToken.toJson();
      storage.user.idToken = session.userPoolTokensResult.value.idToken.toJson();
      storage.user.refreshToken = session.userPoolTokensResult.value.refreshToken;
    }

Our builds are performed through a pipeline. I truly believe that the version has already been updated with the new library version.

Please review and confirm if my understanding is correct. If not, please clarify the correct method. Thank you in advance for your assistance!

@gopbarbosa
Copy link

Hello, @Jordan-Nelson!

Upon conducting a new search, I noticed that I obtained an incorrect build stack trace that used an outdated library. Please find below the new error stack trace.
Captura de Tela 2023-05-29 às 11 30 53
Captura de Tela 2023-05-29 às 11 30 38

It appears to be a connection error, but according to the users, they are able to proceed with the login normally immediately after this error, indicating the need for a valid internet connection.

I'm available for further information or clarification.

@Jordan-Nelson
Copy link
Member

@GarbielBarbosa - Yes, fetchAuthSession is the correct way to obtain the tokens.

It could be that the users experiencing this have a spotty network connection that is causing only some requests to fail. You can handle the network exception case. A network exception indicates that the user's access/id tokes have expired, but the refresh token may still be valid (there is no way to determine the validity of the refresh token while offline). In the Authenticator UI component this case is handled as a valid session while the user is offline. Once they come back online if the refresh token has expired they will then be direct to sign in again. You can see how that is handled below.

Future<bool> isValidSession() async {
return _withUserAgent(() async {
final session =
await Amplify.Auth.fetchAuthSession() as CognitoAuthSession;
final CognitoAuthSession(:userPoolTokensResult) = session;
return switch (userPoolTokensResult) {
// If tokens can be retrieved without an exception, return true.
AuthSuccessResult _ => true,
AuthErrorResult(:final exception) => switch (exception) {
SignedOutException _ => false,
// NetworkException indicates that access and/or id tokens have expired
// and cannot be refreshed due to a network error. In this case the user
// should be treated as authenticated to allow for offline use cases.
NetworkException _ => true,
// Any other exception should be thrown to be handled appropriately.
_ => throw exception,
},
};
});

If you would like further assistance can you please open a new issue since it does not appear that the exception you are seeing is that same as what was reported in the original issue.

@gopbarbosa
Copy link

@Jordan-Nelson,

I kindly request your assistance in reviewing the issue #3130. I would be immensely grateful if you could take a look at it and provide your analysis.

Thank you for your attention and support.

@ilyasarafath
Copy link

getting same issue
for me its getting after signIn accessing storage upload
SessionExpiredException {
E/flutter (13937): "message": "The AWS credentials could not be retrieved",
E/flutter (13937): "recoverySuggestion": "Invoke Amplify.Auth.signIn to re-authenticate the user",
E/flutter (13937): "underlyingException": "NotAuthorizedException {\n message=Token is not from a supported provider of this identity pool.,\n}"
E/flutter (13937): }

@Jordan-Nelson
Copy link
Member

@ilyasarafath the underlying exception in the logs you shared is different than what has been shared for this issue. I think it is likely a different issue. Can you open a new issue so that we can gather all the details about your issue?

@brunovsiqueira
Copy link
Author

brunovsiqueira commented Jun 28, 2023

Hi there.
@Jordan-Nelson have you guys discussed about downgrading the minSdkVersion? We need to migrate to check if the issue persists, but we can't do so without supporting all users.

@Jordan-Nelson
Copy link
Member

Hi @brunovsiqueira - Apologies that this has been taking a while. There are two blockers from supporting these API levels that we are discussing internally:

  1. EncryptedSharedPreferences, used within Auth (as well as other categories), has stable support for 23+
  2. Amplify Android (used within a couple non-auth categories) supports 24+

It is unlikely that we will be able to support API 21/22 because of the blocker on EncryptedSharedPreferences. We are still discussing support for 23.

If we were able to support 23, would this allow you to adopt Amplify flutter v1 or would lack of support for 21/22 still be a blocker?

@Jordan-Nelson
Copy link
Member

@brunovsiqueira - I just wanted to follow up with you and see if supporting API level 23 would unblock you from upgrading. As I had mentioned, I don't think supporting levels 21 & 22 will be possible because of the blocker on EncryptedSharedPreferences.

@brunovsiqueira
Copy link
Author

brunovsiqueira commented Jul 10, 2023

Hi @Jordan-Nelson. Thank you for the follow-up.

Unfortunately, we cannot upgrade the minSdkVersion to 23. We currently have 2,000 active users on API 21 and 22, and for now we cannot stop supporting them.

@Jordan-Nelson
Copy link
Member

Hi @Jordan-Nelson. Thank you for the follow-up.

Unfortunately, we cannot upgrade the minSdkVersion to 23. We currently have 2,000 active users on API 21 and 23, and for now we cannot stop supporting them.

Just to confirm, do you mean API 21 and 22?

@brunovsiqueira
Copy link
Author

Hi @Jordan-Nelson. Thank you for the follow-up.
Unfortunately, we cannot upgrade the minSdkVersion to 23. We currently have 2,000 active users on API 21 and 23, and for now we cannot stop supporting them.

Just to confirm, do you mean API 21 and 22?

Exactly. Sorry for the confusion. I have just updated my comment.

@Jordan-Nelson
Copy link
Member

Okay. We are exploring supporting API 23. If you would like to see 21/22 supported in version 1.x, would you be willing to open a feature request? We can use that to track interest in support for those API levels.

@Jordan-Nelson
Copy link
Member

@brunovsiqueira - I think it makes sense to close this issue out as we believe this has been resolved in v1, and do not plan to address it in v0. If you would like, we can open a feature request to track interest in supporting a lower API level on Android.

@Jordan-Nelson Jordan-Nelson added the pending-close-response-required The issue will be closed if details necessary to reproduce the issue are not provided within 7 days. label Jul 19, 2023
@Jordan-Nelson
Copy link
Member

@brunovsiqueira - I am going to close out this issue. Please feel free to open a request for supporting a lower API level on Android in v1. Please let me know if you have any questions.

@brunovsiqueira
Copy link
Author

brunovsiqueira commented Sep 13, 2023

Hi @Jordan-Nelson @dnys1, how are you?

Our app is currently undergoing migration to support API level 23 (minSdkVersion 23). Is it possible for Amplify Flutter to also support API level 23? If so, we can proceed with migrating to version 1.x.x. This would be greatly appreciated by our team at BTG Pactual.

Additionally, the need to support Amplify versions earlier than 1.0.0 has become a significant challenge due to its dependency on aws_common, which itself relies on http version 0.13.4. Consequently, we are unable to update any dependencies that have moved to http version 1.x.x.

@Jordan-Nelson
Copy link
Member

Hi @brunovsiqueira - You are look for Amplify V1 to support Android API level 23+ for the Auth category only, correct? You had previously asked about API levels 21/22. Are you only looking for API level 23+?

Could you open a new feature request for this, and include those details? Thanks

@brunovsiqueira
Copy link
Author

Hi @brunovsiqueira - You are look for Amplify V1 to support Android API level 23+ for the Auth category only, correct? You had previously asked about API levels 21/22. Are you only looking for API level 23+?

Could you open a new feature request for this, and include those details? Thanks

Thanks for the fast answer. Yes, I am looking for amplify_flutter, amplify_auth_cognito and amplify_core to support API 23. These are the dependencies we have.

I am going to open a feature request.

@brunovsiqueira
Copy link
Author

@Jordan-Nelson I have just created the feature request: #3739.

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 fixed-in-release-candidate Issues that have been addressed in the current release-candidate branch pending-close-response-required The issue will be closed if details necessary to reproduce the issue are not provided within 7 days.
Projects
None yet
Development

No branches or pull requests