AWS Amplify Auth Errors

11k views Asked by At

I'm using the Android Amplify library. I am having trouble finding out what kind of error would be passed back from the Amplify.Auth.signIn() function. I'm not finding the documentation for this anywhere. Right now I am just kind of guessing as to what it will return. What I want is to tell the user how to recover from the error. Does the username not exist, was the password incorrect, was it of bad format, etc. Reading the source code I am given the impression that AmplifyException.recoveryMessage is what I want but that would still be problematic as it doesn't allow me to customize the message.

/**
 * Sign in the user to the back-end service and set the currentUser for this application
 * @param username User's username
 * @param password User's password
 */
override fun initiateSignin(username : String, password : String) {
    //Sign in the user to the AWS back-end
    Amplify.Auth.signIn(
        username,
        password,
        {result ->
            if (result.isSignInComplete) {
                Timber.tag(TAG).i("Sign in successful.")

                //Load the user if the sign in was successful
                loadUser()

            } else {
                Timber.tag(TAG).i("Sign in unsuccessful.")
                //TODO:  I think this will happen if the password is incorrect?

            }
        },
        {error ->
            Timber.tag(UserLogin.TAG).e(error.toString())
            authenticationRecoveryMessage.value = error.recoverySuggestion
        }
    )
}

Authentication recovery message is LiveData that I want to update a snackbar which will tell the user what they need to do for a successful login. I feel there must be some way to get the error from this that I just haven't figured out yet. The ideal way to handle messages to the user is with XML strings for translation possibilities so I would really like to use my own strings in the snackbar but I need to know the things that can go wrong with sign-up and what is being communicated to me through the error -> {} callback.

4

There are 4 answers

5
Azher Aleem On BEST ANSWER

I couldn't find them in the documentation myself, so i decided to log the possibles cases.

 try {
        
        const signInResult = await Auth.signIn({
          username: emailOrPhoneNumber,
          password
        });

        const userId = signInResult.attributes.sub;
        const token =  (await Auth.currentSession()).getAccessToken().getJwtToken();
        console.log(userId, 'token: ', token);
        resolve(new AuthSession(userId, token, false));
      } catch (e) {
        switch (e.message) {
          case 'Username should be either an email or a phone number.':
            reject(`${AuthError.usernameInvalid}:  ${e.message}`);
            break;
          case 'Password did not conform with policy: Password not long enough':
            reject(`${AuthError.passwordTooShort}:  ${e.message}`);
            break;
          case 'User is not confirmed.':
            reject(`${AuthError.userIsNotConfirmed}:  ${e.message}`);
            break;
          case 'Incorrect username or password.':
            reject(`${AuthError.incorrectUsernameOrPassword}:  ${e.message}`);
            break;
          case 'User does not exist.':
            reject(`${AuthError.userDoesNotExist}:  ${e.message}`);
            break;
          default:
            reject(`${AuthError.unknownError}:  ${e.message}`);
        }
      }
1
Marboni On

SignIn uses Cognito's InitiateAuth under the hood, so error codes can be found here:

https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_InitiateAuth.html#API_InitiateAuth_Errors

They are available in the code field of the error.

0
Swaroop Reddy On
import {signIn} from ''aws-amplify/auth';
try {
    const output = await signIn({
      username,
      password
    });
    return output;
  } catch (err: any) {
    if (err.name === 'NotAuthorizedException') {
      console.error('User is not authorized. Check the username and password.');
    }
    console.log('error signing in: ', err.name, err.message);
  }
1
Ben Weber On

You can use this switch case for Auth.signIn()

catch (error) {
      let errorMessage;

      switch (error.name) {
        case 'UserNotFoundException':
          errorMessage = 'User not found. Check email/username.';
          break;
        case 'NotAuthorizedException':
          errorMessage = 'Incorrect password. Try again.';
          break;
        case 'PasswordResetRequiredException':
          errorMessage = 'Password reset required. Check email.';
          break;
        case 'UserNotConfirmedException':
          errorMessage = 'User not confirmed. Verify email.';
          break;
        case 'CodeMismatchException':
          errorMessage = 'Invalid confirmation code. Retry.';
          break;
        case 'ExpiredCodeException':
          errorMessage = 'Confirmation code expired. Resend code.';
          break;
        case 'InvalidParameterException':
          errorMessage = 'Invalid input. Check credentials.';
          break;
        case 'InvalidPasswordException':
          errorMessage = 'Invalid password. Follow policy.';
          break;
        case 'TooManyFailedAttemptsException':
          errorMessage = 'Too many failed attempts. Wait.';
          break;
        case 'TooManyRequestsException':
          errorMessage = 'Request limit reached. Wait and retry.';
          break;
        case 'LimitExceededException':
          errorMessage = 'User pool full. Retry later.';
          break;
        default:
          errorMessage = 'Unknown error. Contact support.';
      }

      return rejectWithValue(error.message);
    }