如何通过电话号码查找AWS Cognito用户以获取其邮箱?
当然有办法啦!AWS Cognito提供了几个实用的API,能帮你通过电话号码查到用户的邮箱,我给你拆解下具体怎么操作:
通过电话号码查找AWS Cognito用户邮箱的方法
方法一:用AdminGetUser直接查询(适用于已知用户名是电话号码的场景)
如果你的用户注册时是用电话号码作为用户名,或者用户池配置了允许电话号码作为登录凭证,且你确认目标用户的用户名就是他的电话号码,那直接调用AdminGetUser就能拿到用户的完整信息,包括邮箱。
关键点:
- 你的服务需要拥有
cognito-idp:AdminGetUser的IAM权限 - 调用时要传入用户池ID和准确的电话号码(格式要和用户注册时一致,比如带国家码
+1234567890)
Python示例代码(用boto3):
import boto3 # 初始化Cognito客户端 cognito_client = boto3.client('cognito-idp') try: # 调用AdminGetUser获取用户信息 user_response = cognito_client.admin_get_user( UserPoolId='你的用户池ID', Username='+1234567890' # 替换为目标用户的电话号码 ) # 从返回的用户属性中提取邮箱 user_email = next((attr['Value'] for attr in user_response['UserAttributes'] if attr['Name'] == 'email'), None) print(f"找到的用户邮箱:{user_email}") except cognito_client.exceptions.UserNotFoundException: print("未找到该电话号码对应的用户")
方法二:用ListUsers筛选查找(更通用的场景)
如果不确定用户的用户名是不是电话号码,或者需要批量筛选,ListUsers支持通过Filter参数按电话号码过滤用户,找到目标用户后就能提取邮箱。
关键点:
- 你的服务需要拥有
cognito-idp:ListUsers的IAM权限 - Filter参数要遵循Cognito的语法,比如匹配电话号码的写法是
phone_number = "+1234567890" - 要考虑分页情况,如果用户池很大,可能需要循环获取结果
Python示例代码(用boto3):
import boto3 cognito_client = boto3.client('cognito-idp') def find_user_email_by_phone(phone_number): pagination_token = None found_email = None while True: # 调用ListUsers接口 list_params = { 'UserPoolId': '你的用户池ID', 'Filter': f'phone_number = "{phone_number}"' } if pagination_token: list_params['PaginationToken'] = pagination_token response = cognito_client.list_users(**list_params) # 遍历返回的用户列表 for user in response['Users']: found_email = next((attr['Value'] for attr in user['Attributes'] if attr['Name'] == 'email'), None) if found_email: print(f"找到用户 {user['Username']},邮箱:{found_email}") return found_email # 检查是否还有分页数据 if 'PaginationToken' not in response: break pagination_token = response['PaginationToken'] print("未找到该电话号码对应的用户") return None # 调用函数查找邮箱 find_user_email_by_phone("+1234567890")
额外提醒
- 一定要保证电话号码的格式和Cognito中存储的完全一致,包括国家码、符号,不然会匹配失败
- 这些都是后台管理级别的API,不能在前端直接调用,必须在你的后端服务中执行,同时要做好权限管控,防止用户信息泄露
- 如果你的用户池开启了电话号码验证,那存储的号码都是经过验证的,匹配成功率更高
内容的提问来源于stack exchange,提问作者YifanL
相关产品推荐
相关产品推荐

