View a markdown version of this page

Usa AdminGetUser con un AWS SDK o CLI - Amazon Cognito

Las traducciones son generadas a través de traducción automática. En caso de conflicto entre la traducción y la version original de inglés, prevalecerá la version en inglés.

Usa AdminGetUser con un AWS SDK o CLI

Los siguientes ejemplos de código muestran cómo utilizar AdminGetUser.

Los ejemplos de acciones son extractos de código de programas más grandes y deben ejecutarse en contexto. Puede ver esta acción en contexto en el siguiente ejemplo de código:

.NET
SDK para .NET
nota

Hay más sobre GitHub. Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS.

/// <summary> /// Get the specified user from an Amazon Cognito user pool with administrator access. /// </summary> /// <param name="userName">The name of the user.</param> /// <param name="poolId">The Id of the Amazon Cognito user pool.</param> /// <returns>Async task.</returns> public async Task<UserStatusType> GetAdminUserAsync(string userName, string poolId) { AdminGetUserRequest userRequest = new AdminGetUserRequest { Username = userName, UserPoolId = poolId, }; var response = await _cognitoService.AdminGetUserAsync(userRequest); Console.WriteLine($"User status {response.UserStatus}"); return response.UserStatus; }
  • Para obtener más información sobre la API, consulte AdminGetUser en AWS SDK para .NET Referencia de API.

C++
SDK para C++
nota

Hay más sobre GitHub. Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS.

Aws::Client::ClientConfiguration clientConfig; // Optional: Set to the AWS Region (overrides config file). // clientConfig.region = "us-east-1"; Aws::CognitoIdentityProvider::CognitoIdentityProviderClient client(clientConfig); Aws::CognitoIdentityProvider::Model::AdminGetUserRequest request; request.SetUsername(userName); request.SetUserPoolId(userPoolID); Aws::CognitoIdentityProvider::Model::AdminGetUserOutcome outcome = client.AdminGetUser(request); if (outcome.IsSuccess()) { std::cout << "The status for " << userName << " is " << Aws::CognitoIdentityProvider::Model::UserStatusTypeMapper::GetNameForUserStatusType( outcome.GetResult().GetUserStatus()) << std::endl; std::cout << "Enabled is " << outcome.GetResult().GetEnabled() << std::endl; } else { std::cerr << "Error with CognitoIdentityProvider::AdminGetUser. " << outcome.GetError().GetMessage() << std::endl; }
  • Para obtener más información sobre la API, consulte AdminGetUser en AWS SDK para C++ Referencia de API.

CLI
AWS CLI

Para obtener un usuario

Lo siguiente admin-get-user El ejemplo obtiene información sobre el nombre de usuario jane@example.com.

aws cognito-idp admin-get-user \ --user-pool-id us-west-2_aaaaaaaaa \ --username jane@example.com

Salida:

{ "Username": "a1b2c3d4-5678-90ab-cdef-EXAMPLE11111", "Enabled": true, "UserStatus": "FORCE_CHANGE_PASSWORD", "UserCreateDate": 1548108509.537, "UserAttributes": [ { "Name": "sub", "Value": "a1b2c3d4-5678-90ab-cdef-EXAMPLE11111" }, { "Name": "email_verified", "Value": "true" }, { "Name": "phone_number_verified", "Value": "true" }, { "Name": "phone_number", "Value": "+01115551212" }, { "Name": "email", "Value": "jane@example.com" } ], "UserLastModifiedDate": 1548108509.537 }

Para obtener más información, consulte Administrar y buscar cuentas de usuario en el Guía para desarrolladores de Amazon Cognito.

  • Para obtener más información sobre la API, consulte AdminGetUser en AWS CLI Referencia de comandos.

Java
SDK para Java 2.x
nota

Hay más sobre GitHub. Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS.

public static void getAdminUser(CognitoIdentityProviderClient identityProviderClient, String userName, String poolId) { try { AdminGetUserRequest userRequest = AdminGetUserRequest.builder() .username(userName) .userPoolId(poolId) .build(); AdminGetUserResponse response = identityProviderClient.adminGetUser(userRequest); System.out.println("User status " + response.userStatusAsString()); } catch (CognitoIdentityProviderException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } }
  • Para obtener más información sobre la API, consulte AdminGetUser en AWS SDK for Java 2.x Referencia de API.

JavaScript
SDK para JavaScript (v3)
nota

Hay más información GitHub. Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS.

const adminGetUser = ({ userPoolId, username }) => { const client = new CognitoIdentityProviderClient({}); const command = new AdminGetUserCommand({ UserPoolId: userPoolId, Username: username, }); return client.send(command); };
  • Para obtener más información sobre la API, consulte AdminGetUser en AWS SDK para JavaScript Referencia de API.

Kotlin
SDK para Kotlin
nota

Hay más sobre GitHub. Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS.

suspend fun getAdminUser( userNameVal: String?, poolIdVal: String?, ) { val userRequest = AdminGetUserRequest { username = userNameVal userPoolId = poolIdVal } CognitoIdentityProviderClient.fromEnvironment { region = "us-east-1" }.use { identityProviderClient -> val response = identityProviderClient.adminGetUser(userRequest) println("User status ${response.userStatus}") } }
  • Para obtener más información sobre la API, consulte AdminGetUser en AWS Referencia del SDK para la API de Kotlin.

Python
SDK para Python (Boto3)
nota

Hay más sobre GitHub. Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS.

class CognitoIdentityProviderWrapper: """Encapsulates Amazon Cognito actions""" def __init__(self, cognito_idp_client, user_pool_id, client_id, client_secret=None): """ :param cognito_idp_client: A Boto3 Amazon Cognito Identity Provider client. :param user_pool_id: The ID of an existing Amazon Cognito user pool. :param client_id: The ID of a client application registered with the user pool. :param client_secret: The client secret, if the client has a secret. """ self.cognito_idp_client = cognito_idp_client self.user_pool_id = user_pool_id self.client_id = client_id self.client_secret = client_secret def sign_up_user(self, user_name, password, user_email): """ Signs up a new user with Amazon Cognito. This action prompts Amazon Cognito to send an email to the specified email address. The email contains a code that can be used to confirm the user. When the user already exists, the user status is checked to determine whether the user has been confirmed. :param user_name: The user name that identifies the new user. :param password: The password for the new user. :param user_email: The email address for the new user. :return: True when the user is already confirmed with Amazon Cognito. Otherwise, false. """ try: kwargs = { "ClientId": self.client_id, "Username": user_name, "Password": password, "UserAttributes": [{"Name": "email", "Value": user_email}], } if self.client_secret is not None: kwargs["SecretHash"] = self._secret_hash(user_name) response = self.cognito_idp_client.sign_up(**kwargs) confirmed = response["UserConfirmed"] except ClientError as err: if err.response["Error"]["Code"] == "UsernameExistsException": response = self.cognito_idp_client.admin_get_user( UserPoolId=self.user_pool_id, Username=user_name ) logger.warning( "User %s exists and is %s.", user_name, response["UserStatus"] ) confirmed = response["UserStatus"] == "CONFIRMED" else: logger.error( "Couldn't sign up %s. Here's why: %s: %s", user_name, err.response["Error"]["Code"], err.response["Error"]["Message"], ) raise return confirmed
  • Para obtener más información sobre la API, consulte AdminGetUser en AWS Referencia de la API del SDK para Python (Boto3).

Swift
SDK para Swift
nota

Hay más sobre GitHub. Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS.

import AWSClientRuntime import AWSCognitoIdentityProvider /// Get information about a specific user in a user pool. /// /// - Parameters: /// - cipClient: The Amazon Cognito Identity Provider client to use. /// - userName: The user to retrieve information about. /// - userPoolId: The user pool to search for the specified user. /// /// - Returns: `true` if the user's information was successfully /// retrieved. Otherwise returns `false`. func adminGetUser(cipClient: CognitoIdentityProviderClient, userName: String, userPoolId: String) async -> Bool { do { let output = try await cipClient.adminGetUser( input: AdminGetUserInput( userPoolId: userPoolId, username: userName ) ) guard let userStatus = output.userStatus else { print("*** Unable to get the user's status.") return false } print("User status: \(userStatus)") return true } catch { return false } }
  • Para obtener más información sobre la API, consulte AdminGetUser en AWS Referencia sobre el SDK para la API Swift.

Para obtener una lista completa de AWS Las guías para desarrolladores del SDK y los ejemplos de código, consulta Uso de este servicio con un AWS SDK. En este tema también se incluye información sobre cómo empezar a utilizar el SDK y detalles sobre sus versiones anteriores.