aws-sdk-android icon indicating copy to clipboard operation
aws-sdk-android copied to clipboard

AWSMobileCLient getTokens returns Exception: No cached session.

Open TobiS97 opened this issue 5 years ago • 22 comments

State your question I followed the Tutorial on https://aws-amplify.github.io/docs/sdk/android/authentication. After a sucessfully calling the signIn Method from the AWSMobileCLient as stated in the tutorial, I get back the message "Tokens are invalid, please sign-in again. Exception: No chached session." The userState of my user is logged in. The essential code:

    AWSMobileClient.getInstance().signIn(username, password, null, new Callback<SignInResult>               () {
        @Override
        public void onResult(final SignInResult signInResult) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Log.d("CognitoService", "Sign-in callback state: " + signInResult
                            .getSignInState());
                    switch (signInResult.getSignInState()) {
                        case DONE:
                            makeToast(context, "Sign-in done.");
                            confirmSignIn();
                            try {
                                Log.d("Debug", AWSMobileClient.getInstance().getTokens().getAccessToken
                                        ().toString());
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            Intent intent = new Intent(getApplicationContext(), MainActivity
                                    .class);
                            startActivity(intent);
                            break;
                        case SMS_MFA:
                            makeToast(context, "Please confirm sign-in with SMS.");
                            break;
                        case NEW_PASSWORD_REQUIRED:
                            makeToast(context, "Please confirm sign-in with new password.");
                            break;
                        default:
                            makeToast(context, "Unsupported sign-in confirmation: "
                                    + signInResult.getSignInState());
                            break;
                    }
                }
            });
        }`

Here the stacktrace of the exception: It is weird that the getTokens() call delegates the logic to a _getHostedUITokens() method, even if I don't use the hosted ui in this setup. I only use the hosted UI when clicking a login with FB button.

02-13 10:44:13.647 28585-28585/com.example.tobi.androidapp W/AWSMobileClient: Tokens are invalid, please sign-in again.
java.lang.Exception: No cached session.
    at com.amazonaws.mobile.client.AWSMobileClient$12.onFailure(AWSMobileClient.java:1818)
    at com.amazonaws.mobileconnectors.cognitoauth.AuthClient.getSession(AuthClient.java:182)
    at com.amazonaws.mobileconnectors.cognitoauth.Auth.getSession(Auth.java:674)
    at com.amazonaws.mobile.client.AWSMobileClient._getHostedUITokens(AWSMobileClient.java:1821)
    at com.amazonaws.mobile.client.AWSMobileClient.access$800(AWSMobileClient.java:161)
    at com.amazonaws.mobile.client.AWSMobileClient$11.run(AWSMobileClient.java:1743)
    at com.amazonaws.mobile.client.internal.InternalCallback.await(InternalCallback.java:115)
    at com.amazonaws.mobile.client.AWSMobileClient.getTokens(AWSMobileClient.java:1717)
    at com.amazonaws.mobile.client.AWSMobileClient.getUserStateDetails(AWSMobileClient.java:1024)
    at com.amazonaws.mobile.client.AWSMobileClient.waitForSignIn(AWSMobileClient.java:903)
    at com.amazonaws.mobile.client.AWSMobileClient$11.run(AWSMobileClient.java:1733)
    at com.amazonaws.mobile.client.internal.InternalCallback.await(InternalCallback.java:115)
    at com.amazonaws.mobile.client.AWSMobileClient.getTokens(AWSMobileClient.java:1699)
    at com.example.tobi.androidapp.LoginActivity$3$1.run(LoginActivity.java:120)
    at android.os.Handler.handleCallback(Handler.java:790)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:164)
    at android.app.ActivityThread.main(ActivityThread.java:6494)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
 Caused by: java.lang.Exception: No cached session
    at com.amazonaws.mobileconnectors.cognitoauth.AuthClient.getSession(AuthClient.java:182) 
    at com.amazonaws.mobileconnectors.cognitoauth.Auth.getSession(Auth.java:674) 
    at com.amazonaws.mobile.client.AWSMobileClient._getHostedUITokens(AWSMobileClient.java:1821) 
    at com.amazonaws.mobile.client.AWSMobileClient.access$800(AWSMobileClient.java:161) 
    at com.amazonaws.mobile.client.AWSMobileClient$11.run(AWSMobileClient.java:1743) 
    at com.amazonaws.mobile.client.internal.InternalCallback.await(InternalCallback.java:115) 
    at com.amazonaws.mobile.client.AWSMobileClient.getTokens(AWSMobileClient.java:1717) 
    at com.amazonaws.mobile.client.AWSMobileClient.getUserStateDetails(AWSMobileClient.java:1024) 
    at com.amazonaws.mobile.client.AWSMobileClient.waitForSignIn(AWSMobileClient.java:903) 
    at com.amazonaws.mobile.client.AWSMobileClient$11.run(AWSMobileClient.java:1733) 
    at com.amazonaws.mobile.client.internal.InternalCallback.await(InternalCallback.java:115) 
    at com.amazonaws.mobile.client.AWSMobileClient.getTokens(AWSMobileClient.java:1699) 
    at com.example.tobi.androidapp.LoginActivity$3$1.run(LoginActivity.java:120) 
    at android.os.Handler.handleCallback(Handler.java:790) 
    at android.os.Handler.dispatchMessage(Handler.java:99) 
    at android.os.Looper.loop(Looper.java:164) 
    at android.app.ActivityThread.main(ActivityThread.java:6494) 
    at java.lang.reflect.Method.invoke(Native Method) 
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438) 
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)

Which AWS Services are you utilizing? I am using the Amplify Android SDK for authenticating my users. Version: 2.16.+ (aws-android-sdk-mobile-client, com.amazonaws:aws-android-sdk-cognitoauth, ...)

Environment(please complete the following information):

Device Information (please complete the following information):

  • Emulated Device: Nexus 6 API 27

TobiS97 avatar Feb 13 '20 11:02 TobiS97

Hey,

It seems this issue is caused by running the non-async getTokens() method on the main UI thread. You can either run it on a background thread or run the version of getTokens that takes a callback:

AWSMobileClient.getInstance().getTokens(Callback)

TrekSoft avatar Feb 21 '20 21:02 TrekSoft

Hi, In my MainActivity I tried to access the tokens with the callback version, but I also get the exception:

2-22 14:54:53.611 6558-6605/com.example.tobi.androidapp D/JWT-error:: java.lang.Exception: No cached session. 02-22 14:54:53.614 6558-6605/com.example.tobi.androidapp D/JWT-error:: java.lang.Exception: No cached session. at com.amazonaws.mobile.client.AWSMobileClient$12.onFailure(AWSMobileClient.java:1818) at com.amazonaws.mobileconnectors.cognitoauth.AuthClient.getSession(AuthClient.java:182) at com.amazonaws.mobileconnectors.cognitoauth.Auth.getSession(Auth.java:674) at com.amazonaws.mobile.client.AWSMobileClient._getHostedUITokens(AWSMobileClient.java:1821) at com.amazonaws.mobile.client.AWSMobileClient.access$800(AWSMobileClient.java:161) at com.amazonaws.mobile.client.AWSMobileClient$11.run(AWSMobileClient.java:1743) at com.amazonaws.mobile.client.internal.InternalCallback$1.run(InternalCallback.java:101) at java.lang.Thread.run(Thread.java:764) Caused by: java.lang.Exception: No cached session

here the corresponding code, where the exception is thrown. I call this in the onCreate method form my MainActivity Class:

 AWSMobileClient.getInstance().getTokens(
            new Callback<Tokens>() {
                @Override
                public void
                onResult(Tokens result) {
                    Log.d("JWT:" , "method Callback");
                    Log.d("JWT: ", result.getAccessToken()
                            .toString());
                    jwtTextView.setText(result.getAccessToken().toString());
                }

                @Override
                public void
                onError(Exception e) {
                    Log.d("JWT-error: ", e.toString());
                    StringWriter sw = new StringWriter();
                    PrintWriter pw = new PrintWriter(sw);
                    e.printStackTrace(pw);
                    String sStackTrace = sw.toString(); // stack trace as a string
                    Log.d("JWT-error: ", sStackTrace);
                }
            });

I do not understand why the AWS SDK calls the method AWSMobileClient._getHostedUITokens, even if I don't use the HostedUi in this Login flow. It shouldn't be a problem that I call "getTokens" within the onCreate method right?

TobiS97 avatar Feb 22 '20 15:02 TobiS97

Gotcha - yeah are you calling it after a successful callback from the AWSMobileClient initialize though?

TrekSoft avatar Feb 24 '20 14:02 TrekSoft

My initialization is done in my starting activity as following:

AWSMobileClient.getInstance().initialize(getApplicationContext(), new
            Callback<UserStateDetails>() {

                @Override
                public void onResult(UserStateDetails userStateDetails) {
                    Log.i("CognitoService", "onResult: " + userStateDetails.getUserState());
                }

                @Override
                public void onError(Exception e) {
                    Log.e("CognitoService", "Initialization error.", e);
                }
            }
    );

I have retried everything with a completeley new emulator and the problem did not appear then. So I guess it was just a problem with a wrong cached state in my emulators. Apparently restarting the app in the emulators over android studio is not enough sometimes... Thanks for your help and sorry for your time expenses.

TobiS97 avatar Feb 25 '20 09:02 TobiS97

Ok gotcha - thanks for the update!

TrekSoft avatar Feb 28 '20 18:02 TrekSoft

Hey @TobiS97 - just wanted to let you know I happened to come across this issue in my own testing and found you are 100% right and it is a bug on our end where once a user has signed in with Hosted UI, it permanently caches that which messes up getting tokens if you sign in with the regular sign in method. We will be fixing this.

TrekSoft avatar Mar 24 '20 19:03 TrekSoft

What version would fix this issue? I'm hitting that problem at the moment.

RafaRuiz avatar Jul 06 '20 13:07 RafaRuiz

Looks like it's in 2.16.10 or later - any reason you can't just use the latest version?

TrekSoft avatar Jul 06 '20 14:07 TrekSoft

@TrekSoft my bad, I've been hitting that problem somehow else. Might not be interesting, but it happened when:

  • logged in with user1
  • logged in with user2 (without calling signOut)
  • logged out with user2
  • tried to log in with user1 -> that error
  • tried to log in with user2 -> success.

I'm calling signOut between the first 2 steps now. Not sure if it's a bug, just letting you know here :)

RafaRuiz avatar Jul 06 '20 14:07 RafaRuiz

Hmm gotcha - and this was with signing in with Hosted UI for both users?

TrekSoft avatar Jul 06 '20 20:07 TrekSoft

Nope, as far as I know (I've never used these SDKs many times, I'm part of a project). I'm using the aws-android-sdk-mobile-client-2.16.12-sources.jar

RafaRuiz avatar Jul 07 '20 08:07 RafaRuiz

Got it - what I'm asking is, how did you sign in the users? What method were you calling to do it?

TrekSoft avatar Jul 07 '20 14:07 TrekSoft

I used this one:

@AnyThread
public void signIn(final String username,
                   final String password,
                   final Map<String, String> validationData,
                   final Callback<SignInResult> callback) {

    final InternalCallback<SignInResult> internalCallback = new InternalCallback<SignInResult>(callback);
    internalCallback.async(_signIn(username, password, validationData, internalCallback));
}

RafaRuiz avatar Jul 07 '20 21:07 RafaRuiz

Hmm, ok - and can you post the specific error you're getting with the stack trace?

TrekSoft avatar Jul 10 '20 15:07 TrekSoft

W/AWSMobileClient: signalTokensNotAvailable W/AWSMobileClient: Tokens are invalid, please sign-in again. java.lang.Exception: No cached session. at com.amazonaws.mobile.client.AWSMobileClient$11$1.signalTokensNotAvailable(AWSMobileClient.java:1801) at com.amazonaws.mobile.client.AWSMobileClient$11$1.getAuthenticationDetails(AWSMobileClient.java:1781) at com.amazonaws.mobileconnectors.cognitoidentityprovider.CognitoUser.getSession(CognitoUser.java:778) at com.amazonaws.mobile.client.AWSMobileClient$11.run(AWSMobileClient.java:1763) at com.amazonaws.mobile.client.internal.InternalCallback.await(InternalCallback.java:115) at com.amazonaws.mobile.client.AWSMobileClient.getTokens(AWSMobileClient.java:1729) at com.amazonaws.mobile.client.AWSMobileClient.getUserStateDetails(AWSMobileClient.java:1031) at com.amazonaws.mobile.client.AWSMobileClient.waitForSignIn(AWSMobileClient.java:910) at com.amazonaws.mobile.client.AWSMobileClient$11.run(AWSMobileClient.java:1745) at com.amazonaws.mobile.client.internal.InternalCallback.await(InternalCallback.java:115) at com.amazonaws.mobile.client.AWSMobileClient.getTokens(AWSMobileClient.java:1711) at com.xxx.xxx.engine.comms.aws.xxx.getTokens(AWSClient.kt:92) at com.xxx.xxx.engine.comms.api.CognitoLoginAPI.getToken(LoginAPI.kt:60) at xxx.xxx.xxx.engine.comms.retrofit.OkHttpClientBuilder$$special$$inlined$invoke$1.intercept(Interceptor.kt:81) at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.kt:100) at okhttp3.internal.connection.RealCall.getResponseWithInterceptorChain$okhttp(RealCall.kt:197) at okhttp3.internal.connection.RealCall$AsyncCall.run(RealCall.kt:502) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641) at java.lang.Thread.run(Thread.java:919) D/AWSMobileClient: waitForSignIn: userState:SIGNED_OUT_USER_POOLS_TOKENS_INVALID

RafaRuiz avatar Jul 10 '20 16:07 RafaRuiz

Alright thanks - we'll look into this. Since it sounds like you're not blocked by it for now we'll keep it as a lower priority item but does sound like something we'll want to ultimately address.

TrekSoft avatar Jul 10 '20 16:07 TrekSoft

Any news on this issue ? I believe it's related to this one https://github.com/aws-amplify/amplify-android/issues/873.

Sserra90 avatar Jan 11 '21 12:01 Sserra90

+1 Any updates on this issue?

fanwgwg avatar Mar 24 '21 18:03 fanwgwg

+1 I'm having exactly the same error. After login with Facebook i'm not able anymore to login with other user using password because it's retuning that Tokens are invalid, please sign-in again.

brunosp15 avatar Mar 29 '21 21:03 brunosp15

When I tired to send the IdToken to api using below code but AWSMobileClient.getInstance().getTokens().getIdToken().getTokenString() gives below error when token expires.

 try { 
                headers.put(AUTHORIZATION, Constants.BEARER_TAG + AWSMobileClient.getInstance().getTokens().getIdToken().getTokenString());
            } catch (Exception e) {
                e.printStackTrace();
            }

2022-09-16 16:41:08.584 4737-4782/ W/AWSMobileClient: signalTokensNotAvailable 2022-09-16 16:41:08.584 4737-4782/ W/System.err: java.lang.Exception: No cached session. 2022-09-16 16:41:08.584 4737-4782/ W/System.err: at com.amazonaws.mobile.client.AWSMobileClient$12$1.f(:2066) 2022-09-16 16:41:08.584 4737-4782/ W/System.err: at com.amazonaws.mobile.client.AWSMobileClient$12$1.a(:2061) 2022-09-16 16:41:08.584 4737-4782/W/System.err: at com.amazonaws.mobileconnectors.cognitoidentityprovider.CognitoUser.F(:1037) 2022-09-16 16:41:08.584 4737-4782/ W/System.err: at com.amazonaws.mobile.client.AWSMobileClient$12.run(:2027) 2022-09-16 16:41:08.584 4737-4782/ W/System.err: at com.amazonaws.mobile.client.internal.InternalCallback.d(:115) 2022-09-16 16:41:08.584 4737-4782/ W/System.err: at com.amazonaws.mobile.client.AWSMobileClient.N(:1975) 2022-09-16 16:41:08.584 4737-4782/ W/System.err: at e.f.a.a.j.f.getHeaders(:142) 2022-09-16 16:41:08.584 4737-4782/ W/System.err: at e.a.a.w.j.b(:79) 2022-09-16 16:41:08.584 4737-4782/ W/System.err: at e.a.a.w.c.a(:123) 2022-09-16 16:41:08.584 4737-4782/ W/System.err: at e.a.a.i.d(:131) 2022-09-16 16:41:08.584 4737-4782/ W/System.err: at e.a.a.i.c(:111) 2022-09-16 16:41:08.584 4737-4782/ W/System.err: at e.a.a.i.run(:90) 2022-09-16 16:41:08.584 4737-4782/W/System.err: Caused by: com.amazonaws.mobileconnectors.cognitoidentityprovider.exceptions.CognitoInternalErrorException: Failed to authenticate user 2022-09-16 16:41:08.584 4737-4782/ W/System.err: at com.amazonaws.mobileconnectors.cognitoidentityprovider.CognitoUser.C(:1312) 2022-09-16 16:41:08.584 4737-4782/ W/System.err: at com.amazonaws.mobileconnectors.cognitoidentityprovider.CognitoUser.F(:1022) 2022-09-16 16:41:08.584 4737-4782/ W/System.err: ... 9 more 2022-09-16 16:41:08.584 4737-4782/ W/System.err: Caused by: com.amazonaws.AmazonClientException: Unable to unmarshall error response (com.amazonaws.services.cognitoidentityprovider.model.NotAuthorizedException. [class java.lang.String]). Response Code: 400, Response Text: Bad Request, Response Headers: {X-Android-Selected-Protocol=http/1.1, x-amzn-ErrorMessage=Invalid Refresh Token., Connection=keep-alive, x-amzn-ErrorType=NotAuthorizedException:, x-amzn-RequestId=cb18cab1-2646-422b-b5a4-d1d537d8f2b1, X-Android-Response-Source=NETWORK 400, X-Android-Sent-Millis=1663326668197, Content-Length=70, X-Android-Received-Millis=1663326668583, Date=Fri, 16 Sep 2022 11:11:09 GMT, Content-Type=application/x-amz-json-1.1} 2022-09-16 16:41:08.584 4737-4782/ W/System.err: at com.amazonaws.http.AmazonHttpClient.h(:736) 2022-09-16 16:41:08.584 4737-4782/ W/System.err: at com.amazonaws.http.AmazonHttpClient.e(:420) 2022-09-16 16:41:08.584 4737-4782/ W/System.err: at com.amazonaws.http.AmazonHttpClient.d(:229) 2022-09-16 16:41:08.584 4737-4782/ W/System.err: at com.amazonaws.services.cognitoidentityprovider.AmazonCognitoIdentityProviderClient.C(:6837) 2022-09-16 16:41:08.584 4737-4782/ W/System.err: at com.amazonaws.services.cognitoidentityprovider.AmazonCognitoIdentityProviderClient.a(:4573) 2022-09-16 16:41:08.584 4737-4782/ W/System.err: at com.amazonaws.mobileconnectors.cognitoidentityprovider.CognitoUser.S(:2868) 2022-09-16 16:41:08.584 4737-4782/ W/System.err: at com.amazonaws.mobileconnectors.cognitoidentityprovider.CognitoUser.C(:1302) 2022-09-16 16:41:08.584 4737-4782/ W/System.err: ... 10 more 2022-09-16 16:41:08.585 4737-4782/ W/System.err: Caused by: java.lang.NoSuchMethodException: com.amazonaws.services.cognitoidentityprovider.model.NotAuthorizedException. [class java.lang.String] 2022-09-16 16:41:08.585 4737-4782/W/System.err: at java.lang.Class.getConstructor0(Class.java:2363) 2022-09-16 16:41:08.585 4737-4782/ W/System.err: at java.lang.Class.getConstructor(Class.java:1759) 2022-09-16 16:41:08.585 4737-4782/ W/System.err: at com.amazonaws.transform.AbstractErrorUnmarshaller.b(:66) 2022-09-16 16:41:08.585 4737-4782/ W/System.err: at com.amazonaws.transform.JsonErrorUnmarshaller.d(:53) 2022-09-16 16:41:08.585 4737-4782/ W/System.err: at com.amazonaws.services.cognitoidentityprovider.model.transform.NotAuthorizedExceptionUnmarshaller.d(:37) 2022-09-16 16:41:08.585 4737-4782/ W/System.err: at com.amazonaws.http.JsonErrorResponseHandler.d(:98) 2022-09-16 16:41:08.585 4737-4782/ W/System.err: at com.amazonaws.http.JsonErrorResponseHandler.c(:67) 2022-09-16 16:41:08.585 4737-4782/ W/System.err: at com.amazonaws.http.JsonErrorResponseHandler.b(:35) 2022-09-16 16:41:08.585 4737-4782/W/System.err: at com.amazonaws.http.AmazonHttpClient.h(:711) 2022-09-16 16:41:08.585 4737-4782/ W/System.err: ... 16 more

I need to send the activeIdToken whenever the api call happens. Please help me out.

suresh-ramasamy002 avatar Sep 16 '22 11:09 suresh-ramasamy002

The error message suggests that either user is not signed in or refresh token is expired. In both cases, the user must login again to get the tokens.

div5yesh avatar Sep 17 '22 00:09 div5yesh

I've found the issue. As it turns out, it was not really an invalid refresh token;

If you have device tracking enabled, then you must pass the users device key in the AuthParameters (which I was not doing).

I read through the description of device tracking, as https://aws.amazon.com/blogs/mobile/tracking-and-remembering-devices-using-amazon-cognito-your-user-pools and it didn't seem applicable for my use-case so I simply turned it off (User Pool > Devices.

Please send the device key in authParameters to make it work incase you enabled device tracking and that should resolve your issues

suresh-ramasamy002 avatar Sep 17 '22 04:09 suresh-ramasamy002

Closing this issue as the issue has been resolved.

eeatonaws avatar Sep 27 '22 18:09 eeatonaws