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

Auth.currentAuthenticatedUser() always return "Not Authenticated" causing Infinite reloads #5167

Closed
akashv-builder opened this issue Mar 23, 2020 · 29 comments
Labels
OAuth For issues related to OAuth question General question

Comments

@akashv-builder
Copy link

akashv-builder commented Mar 23, 2020

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

@akashv-builder akashv-builder added the question General question label Mar 23, 2020
@manueliglesias manueliglesias added OAuth For issues related to OAuth to-be-reproduced Used in order for Amplify to reproduce said issue labels Mar 27, 2020
@zeritte
Copy link

zeritte commented Apr 2, 2020

see #4420. if doesn't help, please provide your amplify-js version

@stale
Copy link

stale bot commented Apr 28, 2020

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

@stale stale bot closed this as completed Apr 28, 2020
@Rolando-Barbella
Copy link

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",

@dhavalsoni2001
Copy link

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

@proevilz
Copy link

"aws-amplify": "^3.0.16",
"expo": "~37.0.9",
"react-native": "https://github.com/expo/react-native/archive/sdk-37.0.1.tar.gz",

Same problem, this needs to be reopened.

@dbaigel1
Copy link

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

@mxswat
Copy link

mxswat commented Aug 10, 2020

I'm looking for a solution too

@janhesters
Copy link

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'

@Rolando-Barbella
Copy link

Rolando-Barbella commented Aug 12, 2020

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

@dylan-westbury
Copy link

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

@IgorMing
Copy link

IgorMing commented Sep 9, 2020

I'm facing the same problem, here. Did anyone find a solution?

{
    "amazon-cognito-identity-js": "^4.3.5",
    "aws-amplify": "^3.0.24",
    "aws-amplify-react-native": "^4.2.5",
    "react": "16.11.0",
    "react-native": "0.62.2"
}

@TheDutchCoder
Copy link

TheDutchCoder commented Sep 28, 2020

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.

@HanggiAnggono
Copy link

HanggiAnggono commented Oct 13, 2020

I'm having this issue as as well, in my case i created the user using admin_create_user with aws-sdk for ruby

@kvdy
Copy link

kvdy commented Oct 28, 2020

I am also facing this issue. For my react routes, I am checking the authentication and it always returns not authenticated.

@Rolando-Barbella
Copy link

@kvdy Maybe you are missing the confirmation step? Auth.confirmSignUp

@phaeton2040
Copy link

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

@SandeshAthreyaBD
Copy link

I'm also facing this issue, I'm using React and it returns "not Authenticated" everytime. I am manually creating users in the user pool and marking the email as "verified" and I still encounter the problem. Is there a solution?

@soorajlv
Copy link

soorajlv commented Nov 30, 2020

Also facing the same issue. User is verified and confirmed. I can see that in the developer tool, amplify is sending proper code challenge and getting access token in return. The problem is, as the @TheDutchCoder said, user data is not getting persisted in the storage. Further debugging shows that the Hub.listen('auth') is not fired from _handleAuthResponse function in node_modules\@aws-amplify\auth\lib\Auth.js, which in turn was not fired after getting back from the login. This is very weird.

@mxswat
Copy link

mxswat commented Nov 30, 2020

I remembered that this infinite reload might happen if the user you are using is not "confirmed" using the phone or email code

@j1mr10rd4n
Copy link

j1mr10rd4n commented Jan 6, 2021

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

@skworden
Copy link

skworden commented Feb 22, 2021

I have the same issue. I'm using nextjs and cookies - aws-cognito-next returns the current authenticated user and this library's currentAuthenticatedUser does not. I'm calling them in the same function too.

Every part of the auth flow works as expected (sign up, confrim, forgot pw, change pw, etc) except the actual login.

@MatteoGioioso
Copy link

same bug here, has this been solved? Last time I have used it was working

@skworden
Copy link

skworden commented Mar 17, 2021

Mine is working now. For me my issues were the following.

Client side can configure with either

import Auth from '@aws-amplify/auth';
Auth.configure(yourCognitoConfig);
Auth.xxx

or

import Amplify from 'aws-amplify';
Amplify .configure({ Auth: yourCognitoConfig });

However, on server side the former did not work for me.

Server side you have to configure from the default export.

import Amplify from 'aws-amplify';
Amplify.configure({ Auth: yourCognitoConfig });

or you can still use the following after you configure with the latter default export.

import Auth from '@aws-amplify/auth';
Auth.xxx

Also, make sure your user is verified.

If you use cookies make sure your exp is a number and not a string. I was pulling it from an env var and not converting it to a number.

Also, in nextjs specifically, you must call configure import Amplify from 'aws-amplify';Amplify.configure({ Auth: yourCognitoConfig }); on every page with server side props call. I called it in the props.

Lastly, when possible I'd try to use @aws-amplify/auth because it's a smaller import.

@gruckionvit
Copy link

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.

@rapgithub
Copy link

with SignInWithApple undefined all the time! only Facebook and google works! :(

@yazoo321
Copy link

I was having the same issue and came across this:
#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.

@repka3
Copy link

repka3 commented Feb 14, 2022

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.

@diegoburland
Copy link

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🥸

@github-actions
Copy link

This issue has been automatically locked since there hasn't been any recent activity after it was closed. Please open a new issue for related bugs.

Looking for a help forum? We recommend joining the Amplify Community Discord server *-help channels or Discussions for those types of questions.

@github-actions github-actions bot locked as resolved and limited conversation to collaborators Feb 26, 2023
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
OAuth For issues related to OAuth question General question
Projects
None yet
Development

No branches or pull requests