Search code examples
angularamazon-cognitoaws-amplifysaml

Detect if user is identified and get the data


I have a website with authentication by SAML. I use the aws-amplify library on this site.
I need to know if the user is identified,
And if not - navigate him to the address of cognito which directs him to the login page of the SAML provider.
So, I used aws-amplify v5 and wrote this code:

Auth.currentAuthenticatedUser().then(cognitoUser => {
  ...
}).catch(e => {
  console.log(e);
  window.location.href = this.redirectLink;
});

When the user was identified - he reached the section inside the then,
And when he was not identified - he reached the section of the catch.

Now I'm trying to upgrade to v6, And I see here that the currentAuthenticatedUser function has been deprecated.
The article suggests using a combination of the getCurrentUser and fetchAuthSession API's.

I tried using both together and each of them separately, But I couldn't get to the point where I can detect whether the user is identified or not.

The getCurrentUser function always falls to the catch with the error "UserUnAuthenticatedException: User needs to be authenticated to call this API."
And the fetchAuthSession function always returns empty properties.

I'm trying to figure out,
Am I doing something wrong?
Am I missing something?
Or is there really no way in this version to know if the user is identified?

Thanks in advance.


Solution

  • Finally,
    I did it like this:

    getCurrentUser().then(currentUser => {
      fetchAuthSession().then(cognitoUserSession => {
         this.doSomething(currentUser, cognitoUserSession);
      });
    })
    .catch(e => {
      signInWithRedirect({
        provider: { custom: "myIdentityProvider" }
      })
    });