amplify-js: Auth.currentAuthenticatedUser() always return "Not Authenticated" causing Infinite reloads

** Which Category is your question related to? ** Correct implementation of Auth.currentAuthenticatedUser() ** What AWS Services are you utilizing? ** Cognito ** Provide additional details e.g. code snippets ** I have a use-case wherein, I first want to check if a user is authenticated or not on the first visit to the site. If the user is not authenticated, I want to redirect the user to the OIDC provider configured at Cognito using Auth.federatedSignIn(). However, I am getting “Not Authenticated” response from the Auth.currentAuthenticatedUser() everything.

This is the function calling Auth.currentAuthenticatedUser():

export function getCurrentUser() {
  console.log("inside getCurrentUser try");
  Auth.currentAuthenticatedUser()
    .then(user => {
      console.log(user);
      return user;
    })
    .catch(ex => {
      console.log(ex);
      console.log("inside getCurrentUser catch, calling federatedSignIn");
      Auth.federatedSignIn({ provider: "Federate" });
    });
}

Now, from the component, I am calling getCurrentUser()

  componentDidMount() {
    try {
      userData = auth.getCurrentUser();
      console.log("I am the data" + userData);
      if (userData) {
        this.props.onAddUserData();
        this.setState({ isLoggedIn: true });
      }
    } catch (ex) {
      console.log(ex);
      console.log("Not logged in. Redirect to OIDC");
    }
  }

The events I am getting in the console:

  1. inside getCurrentUser try
  2. I am the data undefined
  3. not authenticated
  4. inside getCurrentUser catch, calling federatedSignIn

The page is getting refreshed again and again.

About this issue

  • Original URL
  • State: closed
  • Created 4 years ago
  • Reactions: 4
  • Comments: 29

Most upvoted comments

Can’t figure this out either. Happens on the browser.

I literally call:

const user = await Auth.signIn(email, password);
console.log(user); // ✅  is correct
const response = await Auth.currentAuthenticatedUser();
// 🚫  throws 'not authenticated'

I was having the same issue and came across this: https://github.com/aws-amplify/amplify-js/issues/7102

Basically, after signIn if the user has a challenge of ‘NEW_PASSWORD_REQUIRED’, the same problem that @janhesters was having repeats:

const user = await Auth.signIn(email, password);
console.log(user); // ✅  is correct
const response = await Auth.currentAuthenticatedUser();
// 🚫  throws 'not authenticated'

I’ve used this: https://docs.amplify.aws/lib/auth/manageusers/q/platform/js#complete-new-password as a template for a demo app to fix this problem

              const userRes = await Auth.signIn(username, password);
              if (userRes.challengeName === 'NEW_PASSWORD_REQUIRED') {
                Auth.completeNewPassword(
                  userRes,            
                  password,   // pass the same password
                ).then(user => {
                    // at this time the user is logged in if no MFA required
                    console.log(user);
                }).catch(e => {
                  console.log(e);
                });
            } else {
                // other situations
            }

After this, I confirmed that my Hub was receiving the signIn event:

  useEffect(() => {
    Hub.listen('auth', ({ payload: { event, data } }) => {
      switch (event) {
        case 'signIn':
          getUser().then(userData => setUser(userData));
          break;
        case 'cognitoHostedUI':
          getUser().then(userData => setUser(userData));
          break;
        case 'signOut':
          setUser(null);
          break;
        case 'signIn_failure':
        case 'cognitoHostedUI_failure':
          console.log('Sign in failure', data);
          break;
      }
    });

    getUser().then(userData => setUser(userData));
    getSessionInfo();
  }, []);

and with that, I was finally authenticated to make all the requests I needed, like getUser and currentSession

  function getUser() {
    return Auth.currentAuthenticatedUser()
      .then(userData => userData)
      .catch(() => console.log('Not signed in'));
  }

  function getSessionInfo() {
    Auth.currentSession().then(res=>{
      debugger
      let access_token = res.getAccessToken()
      let id_token = res.getIdToken()
      let refresh_token = res.getRefreshToken();

      setAccessToken(access_token);
      setIdToken(id_token);
    })
  }

This problem existed for me because I created these test users in the Cognito UI, which created a 1-time password on those accounts.

Why this issue has been closed? Is there any update on this issue? I am also facing same issue.

please reopen this issue. Was anyone able to solve it?

I was getting similar errors using a Cognito pool configured with an ADFS identity provider and amplify-3.8.8. I was able to get it working with the following config:

When using a custom identity provider - i.e. not one of the pre-baked [ COGNITO | Google | Facebook | LoginWithAmazon | SignInWithApple ] providers, the object passed to Auth.federatedSignIn() should be: { customProvider: "CustomProviderName" } where CustomProvidernName is as configured in the Cognito pool

Additionally, ensure the oauth entry in the object passed to Auth.configure() (from aws-exports.js) includes the following:

{
  ...
  oauth: {
    ...
    scope: ["openid", "email"],
    responseType: "code",
  }
}

The Cognito user pool setup section of the docs has an example of appending to the config.

See also this SO question

We are also facing this issue. For whatever reason the promise resolves with a “not authenticated” value instead of rejecting.

I’m 99% sure this is some sort of botched localStorage lookup because currentAuthenticatedUser isn’t even doing any sort of XHR request.

After you sign up a user, I believe you need to also sign in. For example:

  1. Auth.signUp
  2. Auth.confirmSignUp
  3. Auth.signIn

This problem is because our first users has status NEW_PASSWORD_REQUIRED, we need to change this password

Running this command on your terminal aws cognito-idp admin-set-user-password --user-pool-id xxxxxxxxxx --username xxxxxxxxxx@gmail.com --password dog123123 --permanent

Note: you can to find the --user-pool-id on Aws console > Cognito > Users > General Settings🥸

I dont know if it can help or not someone. In my case I had Auth.currentAuthenticatedUser({ bypassCache: true}).then( (user: CognitoUser) => this.setUser(user), _err => { console.error(_err) this._authState.next(initialAuthState) } first instruction in setUser was localstorage.clear(), for some reason this broke hard the process and always getting console.error(_err) = User is not authenticated. Removed localstorage.clear() everything is fine.

For me it’s fine on the web react project. But in expo (react-native) when i call currentAuthenticatedUser I get;

Possible Unhandled Promise Rejection (id: 1):
"The user is not authenticated"

Same setup works fine for web, I’ve tested with Facebook and Google auth. Normal email sign in, sign up works absolutely fine.

In my case I had MFA turned on and the Auth module was waiting for OTP. I made MFA optional for my user pool and all went OK

To make sure the user is actually full authenticated:

  • Go to the AWS dashboard and click on Cognito ( make sure you are in the correct region )
  • Click on Manage User Pools
  • Go to users and user groups ( left menu )

There you will see the list of users with the email verified or not, remember the user is full verified once they have entered the verification code sent by email

Screen Shot 2020-08-12 at 22 12 57

Screen Shot 2020-08-12 at 22 13 28

Screen Shot 2020-08-12 at 22 13 54

Same for me, can’t bring the user data, the error message it’s probably wrong as well

“aws-amplify”: “^3.0.5”, “aws-amplify-react”: “^4.1.4”, “aws-appsync”: “^3.0.2”,