Boto3代码返回成功响应但AWS控制台无用户更新问题排查
Boto3代码返回成功响应但AWS控制台无用户更新问题排查
我有一段用于在AWS Cognito中注册用户的代码:
async def _sign_up(self, preferred_username: str, username: str, password: str): ''' Sign up a user with Cognito :param username -> user's username (either email or phone no.) :password -> user's password :return -> Success Response on successful signup. ''' try: signup_response = self._cognito_client.sign_up( ClientId = os.getenv("AWS_COGNITO_APP_CLIENT_ID"), Username = username, Password = password, UserAttributes = [{'Name': 'preferred_username', 'Value':f'{preferred_username}'}] ) if signup_response.get('ResponseMetadata').get('HTTPStatusCode') == 200: try: confirm_signup_response = self._cognito_client.admin_confirm_sign_up( UserPoolId = os.getenv("AWS_COGNITO_USER_POOL_ID"), Username = username, ) if confirm_signup_response.get("ResponseMetadata").get("HTTPStatusCode") == 200: signin_response = await self._sign_in( username = username, password = password ) logger.debug(signin_response) return signin_response except self._cognito_client.exceptions.NotAuthorizedException: return Exception("Invalid username or password.") except self._cognito_client.exceptions.UserNotFoundException: return Exception("User not found.") except self._cognito_client.exceptions.TooManyRequestsException: return Exception("Request limit exceeded.") except self._cognito_client.exceptions.InternalErrorException: return Exception("Something went wrong. Please try after sometime.") except Exception as e: return Exception("Failed to Signin. Please try after some time.", str(e)) except self._cognito_client.exceptions.UsernameExistsException: return Exception("The username already exists.") except self._cognito_client.exceptions.TooManyRequestsException: return Exception("Request limit exceeded.") except self._cognito_client.exceptions.InternalErrorException: return Exception("Something went wrong. Please try after sometime.") except Exception as e: return Exception("Failed to SignUp. Please try after some time.", str(e))
当我调用API时,服务器控制台显示200 OK响应,但控制台里看不到任何新用户,而且我得到的输出是空对象。我已经检查过_cognito_client的配置,确认是没问题的。这可能是什么问题呢?
问题排查思路
- 确认用户池匹配:检查代码中
os.getenv("AWS_COGNITO_USER_POOL_ID")获取的ID和你在控制台查看的用户池是否一致,很容易不小心切换到测试/其他环境的用户池导致看不到用户。 - 验证
sign_up实际结果:别只依赖HTTP状态码,打印signup_response的完整内容,看看有没有UserSub这类用户标识字段,确认用户是否真的被创建了——有时候状态码200但实际存在隐性的参数错误。 - 检查用户状态筛选:即使调用了
admin_confirm_sign_up,用户也可能处于未验证或其他状态。去Cognito控制台的「用户和组」页面,切换状态筛选器,看看是否有隐藏在非「已确认」状态下的用户。 - 权限验证:虽然客户端配置没问题,但要确认执行
sign_up和admin_confirm_sign_up的凭证是否有对应权限——比如admin_confirm_sign_up需要cognito-idp:AdminConfirmSignUp权限,IAM角色或用户凭证缺失这个权限的话,可能会出现表面成功实际未生效的情况。 - 异步代码执行检查:你的
_sign_up是异步函数,admin_confirm_sign_up是同步调用,这里没问题,但要确认_sign_in函数是否正常执行。可以在signin_response处增加日志打印,看看是否获取到了有效响应,会不会是登录环节出了未捕获的异常导致返回空对象。 - 环境变量取值验证:打印
os.getenv("AWS_COGNITO_APP_CLIENT_ID")和os.getenv("AWS_COGNITO_USER_POOL_ID")的实际值,确认环境变量是否正确加载,避免因为变量为空或错误导致调用了无效的资源。
备注:内容来源于stack exchange,提问作者Kushal Patel
相关产品推荐
相关产品推荐

