AWS 放大身份验证错误

AWS Amplify Auth Errors

我正在使用 Android Amplify 库。我无法确定 Amplify.Auth.signIn() 函数会传回哪种错误。我在任何地方都找不到这方面的文档。现在我只是在猜测它会是什么 return。我想要的是告诉用户如何从错误中恢复。用户名是否不存在,密码是否错误,格式是否错误等。阅读源代码给我的印象是 AmplifyException.recoveryMessage 是我想要的,但这仍然是有问题的,因为它不允许我来自定义消息。

/**
 * 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
        }
    )
}

身份验证恢复消息是 LiveData 我想更新一个 snackbar,它将告诉用户他们需要做什么才能成功登录。我觉得一定有某种方法可以从中得到我还没有弄清楚的错误。处理给用户的消息的理想方式是使用 XML 字符串进行翻译,所以我真的很想在小吃栏中使用我自己的字符串,但我需要知道注册时可能出现的问题以及什么正在通过 error -> {} 回调与我沟通。

我自己在文档中找不到它们,所以我决定记录可能的情况。

 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}`);
        }
      }

SignIn 在后台使用 Cognito 的 InitiateAuth,因此可以在此处找到错误代码:

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

它们在错误的 code 字段中可用。