AWS Amplify Auth Errors
S

4

10

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.

Sherronsherry answered 5/12, 2020 at 17:47 Comment(2)
Any luck? I am looking for same. The docs are really disappointing.Subtract
@Subtract No sadly. I would suggest reading the class of error in the callback then working backwards to see the general idea of exceptions that could be thrown. Finally, just test the system and see what is thrown under certain circumstances. This is the best I could do for the time being. They are commented in the source it's just there is not a lot of information on what will cause which to be thrown.Sherronsherry
S
6

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}`);
        }
      }
Subrogate answered 10/1, 2021 at 10:55 Comment(5)
Thanks, I think this is the best we can do for now. This is similar to what I ended up doing in Android.Sherronsherry
@Sherronsherry no worries! Guess cognito should provide an enum containing all the auth errors.Subrogate
do you have similar list for signup function? i could find UsernameExistsException & InvalidPasswordExceptionEllissa
@KaustuvPrajapati, I can check, Do you need one for sign up only?Subrogate
I would be great if there is a list for which exceptions could occur from server on different amplify function such as Amplify.Auth.signup() or .signIn() or .logout(). Its not clear in doc that what exceptions could occur on all of the these functions.Ellissa
C
5

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.

Curlpaper answered 31/3, 2021 at 4:20 Comment(1)
Both code and name work for thisJoshuajoshuah
M
0

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);
    }
Milo answered 26/3, 2023 at 11:12 Comment(1)
As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.Stclair
D
0
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);
  }
Deed answered 7/3 at 7:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.