为什么 Cognito 的 admin-get-user 如果是外部用户,会报告用户不存在?

问题描述 投票:0回答:1

我可以在 AWS Cognito 控制台中看到一个用户

[email protected]
。但是当我尝试使用
admin-get-user
访问该用户时,我得到
UserNotFoundException
。这是我想要做的事情的Python代码:

import boto3

# Initialize the Cognito client with the specified profile
session = boto3.Session(profile_name='Profile_Name')
client = session.client('cognito-idp', region_name='us-east-1')

# Get the user details
try:
    response = client.admin_get_user(
        UserPoolId='user-pool-id',
        Username='[email protected]'
    )

    # Extract the email and creation time
    email = response['UserAttributes'][2]['Value']
    created_at = response['UserCreateDate'].strftime('%Y-%m-%d %H:%M:%S')

    # Print the user details
    print(f"Email: {email}, Created At: {created_at}")
except client.exceptions.UserNotFoundException:
    print("User not found")

上述代码的输出是

User not found


认为可能是cognito sdk过滤了外部用户,我尝试了

list-users
。该代码能够轻松获得用户。代码如下:

import boto3

# Initialize the Cognito client with the specified profile
session = boto3.Session(profile_name='Profile_Name')
client = session.client('cognito-idp', region_name='us-east-1')

# Get all users in the user pool
user_info = []
pagination_token = None

while True:
    # Get users with pagination
    if (pagination_token != None):
      response = client.list_users(
          UserPoolId='user-pool-id',
          AttributesToGet=['email'],
          PaginationToken=pagination_token
      )
    else:
      response = client.list_users(
        UserPoolId='user-pool-id',
        AttributesToGet=['email'],
      )

    # Extract the emails from the response
    for user in response['Users']:
      # print(user)
      user_info.append({
          'email': user['Attributes'][0]['Value'],
          'created_at': user['UserCreateDate'].strftime('%Y-%m-%d %H:%M:%S')
      })

    # Check if there are more users to fetch
    if 'PaginationToken' in response:
        pagination_token = response['PaginationToken']
    else:
        break

print("List of emails and creation times:")
for info in user_info:
    print(f"Email: {info['email']}, Created At: {info['created_at']}")

# Check if the specified email is in the list
target_email = '[email protected]'
is_email_present = any(info['email'] == target_email for info in user_info)

# Print the result
print(f"Email {target_email} is present: {is_email_present}")

这里奇怪的是

admin-get-user
的文档说它应该适用于任何用户:

以管理员身份获取用户池中按用户名指定的用户。 适用于任何用户。

我需要帮助来解决这个问题。否则,我必须使用

list-users
来获取所有用户,以便我可以获得有关我想要的用户的详细信息。

python amazon-web-services amazon-cognito
1个回答
0
投票

对于来自外部提供商的用户,在 admin_get_user 中适合我的用户名是 f"{身份提供商 ID}_{电子邮件}"。也可以在 AWS 控制台的 Cognito 用户列表中的用户名中看到。

© www.soinside.com 2019 - 2024. All rights reserved.