首页 > 解决方案 > Boto3 initial_auth 在使用preferred_username 作为别名时引发NotAuthorizedException 异常

问题描述

我在使用 AWS CognitoIDP 时遇到了一些问题。正如在此处发布的那样,我已设置preferred_username为别名,但在注册用户并设置他/她的首选用户名后,我无法使用密码登录。

我使用preferred_username 创建了一个用户,并将用户名作为一些内部UUID 字符串。用户反映在 cognito 用户池中,并使用 preSignUp 触发器确认。

注册模块

def sign_up(self, uuid_username, username, password):
    self.cognito_client.sign_up(
        ClientId=self.cpcid,
        SecretHash=self.get_secret_hash(uuid_username),
        Username=uuid_username,
        Password=password
    )
    user_attributes = [
        {
            'Name': CognitoAttr.PREFERRED_USERNAME.value,
            'Value': username
        }
    ]
    self.cognito_client.admin_update_user_attributes(
        UserPoolId=self.cpid,
        Username=username,
        UserAttributes=user_attributes
    )
    return

登录模块:

def sign_in(self, username, password, handle_exception=True, **kwargs):
"""

:param username: preferred_username/username of user
:param password: password of user
:param handle_exception: if false, raises cognito exception
:param kwargs:
:return:
"""
try:
    LOGGER.info("Initiate Auth Started")

    response = self.cognito_client.initiate_auth(
        AuthFlow='USER_PASSWORD_AUTH', # with CUSTOM_AUTH, it's working because of defineAuth trigger
        AuthParameters={
            'USERNAME': username,
            'PASSWORD': password,
            'SECRET_HASH': self.get_secret_hash(username)
        },
        ClientId=self.cpcid,
    )
    LOGGER.info("Initiate Auth Ended")
    return self.encrypt_cognito_tokens(
        response["AuthenticationResult"]
    )
except ClientError as err:
    if not handle_exception:
        raise err
    return self.handle_boto3_exception(err)

不工作

上下文:USER_PASSWORD_AUTH 流和登录(boto3 的initiate_auth)preferred_username作为username参数的输入以及密码。

错误:NotAuthorizedException:调用 InitiateAuth 操作时发生错误(NotAuthorizedException):用户名或密码不正确。

工作

上下文:设置一个defineAuthLambda设置为 True 的函数issueTokens,并使用流程登录(boto3 的initiate_auth)CUSTOM_AUTH,提供preferred_usernameusername作为用户名的输入(提供令牌响应)。

此外,admin_get_userCognito boto3 还返回使用用户名和首选用户名的响应。

谁能帮助我可能做错了什么?

标签: amazon-web-servicesauthenticationamazon-cognito

解决方案


推荐阅读