Amplify-js: Auth.currentSession() returning 'No current User' intermittently

Created on 29 Aug 2019  Â·  14Comments  Â·  Source: aws-amplify/amplify-js

Describe the bug

Context: Angular.io application using cognito user pool and dynamodb.

Everything works find most of the time, and I cannot reproduce the error at will. However, other users are receiving errors in production and we're capturing them through our implementation of rollbar.

We've tracked it down to the following code:

try {
  const cognitoUserSession: CognitoUserSession = await Auth.currentSession();
  const idToken = cognitoUserSession.getIdToken();
  return idToken.getJwtToken();
} catch (e) {
    // dump local storage for review
    const localStorage = window.localStorage;
    for (const key of Object.keys(localStorage)) {
      const value = localStorage[key].substring(0, 20);
      this.messageService.add(`${key} ${value}`);
    }
    throw new Error(`Auth.currentSession - Error ${e}`);
}

Intermittently Auth.currentSession() throws an error: 'No current user'

I've reviewed the amplity-js code, for the error message. It seems to happen when the current user cannot be retrieved from the window.local storage.

/**
* Get current authenticated user
* @return - A promise resolves to current authenticated CognitoUser if success
*/
public currentUserPoolUser(params?: CurrentUserOpts): Promise {
if (!this.userPool) { return this.rejectNoUserPool(); }
const that = this;
return new Promise((res, rej) => {
this._storageSync.then(() => {
const user = that.userPool.getCurrentUser();
if (!user) {
logger.debug('Failed to get user from user pool');
rej('No current user');
return;
}

            // refresh the session if the session expired.
            user.getSession((err, session) => {
                if (err) {
                    logger.debug('Failed to get the user session', err);
                    rej(err);
                    return;
                }

However, in my error handler I've logged the key pairs in local storage and they exist.

I'm looking for any help as to what might be causing this.
Thanks again for you help.

Desktop (please complete the following information):

  • OS: Windows
  • Browser chrome
  • Version 76

You can turn on the debug mode to provide more info for us by setting window.LOG_LEVEL = 'DEBUG'; in your app.

Angular Auth pending-close-response-required

Most helpful comment

I had this problem because I was trying to recover the session of a user who still did not have a password set (it was created by the admin on the aws console)

My solution:

if (user.challengeName === 'NEW_PASSWORD_REQUIRED') {
   Auth.completeNewPassword(user, 'NEW_PASSWORD')
  .then(() => {
    this.handleCurrentSession()
   })
} else {
  this.handleCurrentSession()
}

All 14 comments

Here is the data captured with Amplify.Logger.LOG_LEVEL = 'DEBUG'
19:03:52.602 11.415s Log [DEBUG] 03:52.602 AuthClass - Getting current session
19:03:52.602 0.000s Log [DEBUG] 03:52.602 AuthClass - Failed to get user from user pool
19:03:52.616 0.014s Log [DEBUG] 03:52.616 AuthClass - Failed to get the current user No current user

Can we enhance error catching on userPool.getCurrentUser so that get local storage errors are not "hidden" and replaced by the generic "No current user"

                const user = that.userPool.getCurrentUser();
                if (!user) {
                    logger.debug('Failed to get user from user pool');
                    rej('No current user');
                    return;
                }

@singulli1 it could be a chance that your App is calling Auth.currentSession() when the users are logged out or didn't sign in yet?

The error is usually received by processes running on an interval timer after a period of time. We suspect some type of "failed to load resource: net::ERR_NETWORK_IO_SUSPENDED" but this type of error message is 'hidden' by the current code and replaced with "No current User".

I think changing the error handling would help others with these type of problems.

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.

Hi - I've also been getting this same error in the way that @singulli1 describes. Been following/subscribed to this thread in case solutions came up — but seems the stale bot might close this soon.

@singulli1 were you able to figure out what was causing this error for you? Agreed that changing how Amplify handles error handling here would be useful to get a more specific signal of what might be going wrong.

Let me know if there's any workarounds or fixes found. Thanks!

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.

This issue has been automatically closed because of inactivity. Please open a new issue if are still encountering problems.

I need this bot to reopen this, after activating debug logger I'm getting this:
I am using AWS Cognito User Pool, a create-react-app...and that's it

I have spent 5 hours and still can't figure out to persist auth in my web react app.

[DEBUG] 53:23.787 AuthClass - signIn new password
ConsoleLogger.ts:91 [DEBUG] 53:23.989 AuthClass - Getting current session
ConsoleLogger.ts:91 [DEBUG] 53:23.991 AuthClass - getting current authenticated user
ConsoleLogger.ts:91 [DEBUG] 53:23.992 AuthClass - Failed to get user from user pool
ConsoleLogger.ts:91 [DEBUG] 53:23.993 AuthClass - cannot load federated user from auth storage
ConsoleLogger.ts:91 [DEBUG] 53:23.993 AuthClass - get current authenticated userpool user
ConsoleLogger.ts:91 [DEBUG] 53:23.993 AuthClass - Failed to get user from user pool
ConsoleLogger.ts:99 [DEBUG] 53:23.993 AuthClass - Failed to get the current user No current user
ConsoleLogger.ts:99 [DEBUG] 53:23.994 AuthClass - The user is not authenticated by the error No current user
ConsoleLogger.ts:99 [DEBUG] 53:23.994 fuck - currentSession: No current user
ConsoleLogger.ts:99 [DEBUG] 53:23.994 fuck - current auth user: not authenticated

I am facing the same any solution?

I am facing the same issue. I have searched a lot , still no solution.

I had this problem because I was trying to recover the session of a user who still did not have a password set (it was created by the admin on the aws console)

My solution:

if (user.challengeName === 'NEW_PASSWORD_REQUIRED') {
   Auth.completeNewPassword(user, 'NEW_PASSWORD')
  .then(() => {
    this.handleCurrentSession()
   })
} else {
  this.handleCurrentSession()
}

I'm having the same issue, Auth.currentSession() work intermittently as if sometimes it can't retrieve the data.

Here is my best guess....hope it helps some folks out:

1) Amplify uses shared browser storage - window.localStorage to store security tokens by default.
2) Any browser application can call window.localStorage.clear() (say as part of logging out)
3) It seems possible to impact the operation of application A (open in browser tab 1) by running application B (in tab 2) - for example, application B calls window.localStorage.clear() while application A is still running.
4) If this is all true, it's not perfectly stable to store your security tokens in local storage (or perfectly secure).
5) We implemented the custom storage option delivered by Amplify which allows security tokens to be stored in application memory instead of the browser local storage.
6) This seems to have fixed the issue.

Example: configuration:
const currentConfig = Auth.configure({
Auth: {
storage: new AuthStorage(this.customStorage),
region: amplifyConfigPsykdesk.region,
userPoolId: amplifyConfigPsykdesk.userPoolId,
userPoolWebClientId: amplifyConfigPsykdesk.userPoolWebClientId,
mandatorySignIn: amplifyConfigPsykdesk.mandatorySignIn,
authenticationFlowType: amplifyConfigPsykdesk.authenticationFlowType
}
});

Amplify Documentation:
See: https://docs.amplify.aws/lib/auth/manageusers/q/platform/js#managing-security-tokens
Managing security tokens

Was this page helpful?
0 / 5 - 0 ratings