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

AWSMobileCLient getTokens returns Exception: No cached session. #1469

Closed
TobiS97 opened this issue Feb 13, 2020 · 23 comments
Closed

AWSMobileCLient getTokens returns Exception: No cached session. #1469

TobiS97 opened this issue Feb 13, 2020 · 23 comments
Assignees
Labels
bug Something isn't working closing soon Issue will auto-close if there is no additional activity within 7 days. mobile client Issues with AWS Mobile's client-side Cognito wrapper pending-community-response Issue is pending response from the issue requestor

Comments

@TobiS97
Copy link

TobiS97 commented Feb 13, 2020

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
@TrekSoft TrekSoft added mobile client Issues with AWS Mobile's client-side Cognito wrapper bug Something isn't working labels Feb 17, 2020
@TrekSoft
Copy link
Contributor

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 TrekSoft added the pending-community-response Issue is pending response from the issue requestor label Feb 21, 2020
@TrekSoft TrekSoft self-assigned this Feb 21, 2020
@TobiS97
Copy link
Author

TobiS97 commented Feb 22, 2020

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?

@TrekSoft
Copy link
Contributor

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

@TobiS97
Copy link
Author

TobiS97 commented Feb 25, 2020

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 TobiS97 closed this as completed Feb 25, 2020
@TrekSoft
Copy link
Contributor

Ok gotcha - thanks for the update!

@TrekSoft
Copy link
Contributor

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.

@RafaRuiz
Copy link

RafaRuiz commented Jul 6, 2020

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

@TrekSoft
Copy link
Contributor

TrekSoft commented Jul 6, 2020

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

@RafaRuiz
Copy link

RafaRuiz commented Jul 6, 2020

@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 :)

@TrekSoft
Copy link
Contributor

TrekSoft commented Jul 6, 2020

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

@RafaRuiz
Copy link

RafaRuiz commented Jul 7, 2020

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

@TrekSoft
Copy link
Contributor

TrekSoft commented Jul 7, 2020

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

@RafaRuiz
Copy link

RafaRuiz commented Jul 7, 2020

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));
}

@TrekSoft
Copy link
Contributor

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

@RafaRuiz
Copy link

RafaRuiz commented Jul 10, 2020

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

@TrekSoft
Copy link
Contributor

TrekSoft commented Jul 10, 2020

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.

@Sserra90
Copy link

Any news on this issue ? I believe it's related to this one aws-amplify/amplify-android#873.

@fanwgwg
Copy link

fanwgwg commented Mar 24, 2021

+1 Any updates on this issue?

@brunosp15
Copy link

+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.

@suresh-ramasamy002
Copy link

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.

@div5yesh div5yesh reopened this Sep 16, 2022
@div5yesh
Copy link
Contributor

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 div5yesh added the closing soon Issue will auto-close if there is no additional activity within 7 days. label Sep 17, 2022
@suresh-ramasamy002
Copy link

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

@eeatonaws
Copy link
Contributor

Closing this issue as the issue has been resolved.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working closing soon Issue will auto-close if there is no additional activity within 7 days. mobile client Issues with AWS Mobile's client-side Cognito wrapper pending-community-response Issue is pending response from the issue requestor
Projects
None yet
Development

No branches or pull requests

9 participants