NotAuthorizedException in Cognito by using vanilla JavaScript

110 Views Asked by At

I am using amazon-cognito-identity.min.js file got from NPM package and import in HTML page like mentioned below.

  • Got help from here.

  • <script src="cognito-identity-js/amazon-cognito-identity.min.js"></script>

Setups:

  • I set up Userpool in Cognito and used Custom UI for signUp and Login pages.
  • I did Signup and got a verification code to the user email and verified the email on Cognito.
  • When I use to login ( Authenticate User) every time I got errror.

Error:

 NotAuthorizedException: Incorrect username or password. 

I checked multiple time the email and password for any type of typo but still got this error.

Here is my Login function:

function getCognitoUserPool() {
  const userPoolId = 'xxxx'; // Replace with your User Pool ID
  const clientId = 'xxxxx'; // Replace with your App Client ID

  return new AmazonCognitoIdentity.CognitoUserPool({

    UserPoolId: userPoolId,
    ClientId: clientId,
  });
}

// Function to sign in a user to Cognito
async function signInUser(email, password) {
  try {
    const authenticationData = {
      Username: email,
      Password: password,
    };
    const authenticationDetails = new AmazonCognitoIdentity.AuthenticationDetails(authenticationData);

    const userPool = getCognitoUserPool();
    const userData = {
      Username: email,
      Pool: userPool
    };

    console.log(email, password)
    const cognitoUser = new AmazonCognitoIdentity.CognitoUser(userData);

    return new Promise((resolve, reject) => {
      cognitoUser.authenticateUser(authenticationDetails, {
        onSuccess: (session) => {
          resolve(session);
        },
        onFailure: (err) => {
          reject(err);
        },
      });
    });
  } catch (err) {
    throw err;
  }
}



const loginForm = document.getElementById('loginForm');
if (loginForm) {
  loginForm.addEventListener('submit', async (event) => {
    event.preventDefault();
    const email = document.getElementById('loginUseremail').value;
    const password = document.getElementById('loginPassword').value;

    try {
      const session = await signInUser(email, password);
      const jwtToken = session.getIdToken().getJwtToken();
      console.log('User login successful. JWT Token:', jwtToken);
      console.log('Login successful:', session);
      // Do something after successful login (e.g., redirect to a dashboard)
    } catch (err) {
      console.error('Login failed:', err);
    }
  });
};


1

There are 1 best solutions below

0
On BEST ANSWER

Try different ways but at last, I found that I had enabled MFA for SignIn, and the AWS SNS was not configured to send an SMS code to the phone number that why I got the error.

Solution

1: you can turn off MFA for SignIn ( login) in AWS cognito Userpool.

OR

2: if You want to use MFA in SignIn then configure AWS SNS.