Há mais exemplos do AWS SDK disponíveis no repositório do GitHub Documento de Exemplos do AWS SDK
Usar RespondToAuthChallenge com o AWS SDK ou a CLI
Os exemplos de código a seguir mostram como usar o RespondToAuthChallenge.
Exemplos de ações são trechos de código de programas maiores e devem ser executados em contexto. É possível ver essa ação em contexto no seguinte exemplo de código:
- CLI
-
- AWS CLI
-
Exemplo 1: como responder ao desafio NEW_PASSWORD_REQUIRED
O exemplo de
respond-to-auth-challengea seguir responde a um desafio NEW_PASSWORD_REQUIRED que initiate-auth retornou. Ele define uma senha para o usuáriojane@example.com.aws cognito-idp respond-to-auth-challenge \ --client-id1example23456789\ --challenge-nameNEW_PASSWORD_REQUIRED\ --challenge-responsesUSERNAME=jane@example.com,NEW_PASSWORD=[Password]\ --sessionAYABeEv5HklEXAMPLESaída:
{ "ChallengeParameters": {}, "AuthenticationResult": { "AccessToken": "ACCESS_TOKEN", "ExpiresIn": 3600, "TokenType": "Bearer", "RefreshToken": "REFRESH_TOKEN", "IdToken": "ID_TOKEN", "NewDeviceMetadata": { "DeviceKey": "us-west-2_a1b2c3d4-5678-90ab-cdef-EXAMPLE11111", "DeviceGroupKey": "-wt2ha1Zd" } } }Consulte mais informações em Authentication no Guia do desenvolvedor do Amazon Cognito.
Exemplo 2: como responder a um desafio SELECT_MFA_TYPE
O exemplo de
respond-to-auth-challengea seguir escolhe a MFA TOTP como a opção de MFA para o usuário atual. O usuário foi solicitado a selecionar um tipo de MFA e, depois, será solicitado a inserir o código da MFA.aws cognito-idp respond-to-auth-challenge \ --client-id1example23456789--sessionAYABeEv5HklEXAMPLE--challenge-nameSELECT_MFA_TYPE--challenge-responsesUSERNAME=testuser,ANSWER=SOFTWARE_TOKEN_MFASaída:
{ "ChallengeName": "SOFTWARE_TOKEN_MFA", "Session": "AYABeEv5HklEXAMPLE", "ChallengeParameters": { "FRIENDLY_DEVICE_NAME": "transparent" } }Consulte mais informações em Adding MFA no Guia do desenvolvedor do Amazon Cognito.
Exemplo 3: como responder a um desafio SOFTWARE_TOKEN_MFA
O exemplo de
respond-to-auth-challengea seguir fornece um código de MFA TOTP e conclui o login.aws cognito-idp respond-to-auth-challenge \ --client-id1example23456789\ --sessionAYABeEv5HklEXAMPLE\ --challenge-nameSOFTWARE_TOKEN_MFA\ --challenge-responsesUSERNAME=testuser,SOFTWARE_TOKEN_MFA_CODE=123456Saída:
{ "AuthenticationResult": { "AccessToken": "eyJra456defEXAMPLE", "ExpiresIn": 3600, "TokenType": "Bearer", "RefreshToken": "eyJra123abcEXAMPLE", "IdToken": "eyJra789ghiEXAMPLE", "NewDeviceMetadata": { "DeviceKey": "us-west-2_a1b2c3d4-5678-90ab-cdef-EXAMPLE11111", "DeviceGroupKey": "-v7w9UcY6" } } }Consulte mais informações em Adding MFA no Guia do desenvolvedor do Amazon Cognito.
-
Consulte detalhes da API em RespondToAuthChallenge
na Referência de comandos da AWS CLI.
-
- JavaScript
-
- SDK para JavaScript (v3)
-
nota
Há mais no GitHub. Encontre o exemplo completo e veja como configurar e executar no AWS Code Examples Repository
. const respondToAuthChallenge = ({ clientId, username, session, userPoolId, code, }) => { const client = new CognitoIdentityProviderClient({}); const command = new RespondToAuthChallengeCommand({ ChallengeName: ChallengeNameType.SOFTWARE_TOKEN_MFA, ChallengeResponses: { SOFTWARE_TOKEN_MFA_CODE: code, USERNAME: username, }, ClientId: clientId, UserPoolId: userPoolId, Session: session, }); return client.send(command); };-
Consulte detalhes da API em RespondToAuthChallenge na Referência da API AWS SDK para JavaScript.
-
- Python
-
- SDK para Python (Boto3).
-
nota
Há mais no GitHub. Encontre o exemplo completo e veja como configurar e executar no AWS Code Examples Repository
. Faça login com um dispositivo rastreado. Para concluir o login, o cliente deve responder corretamente aos desafios de Secure Remote Password (SRP).
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_in_with_tracked_device( self, user_name, password, device_key, device_group_key, device_password, aws_srp, ): """ Signs in to Amazon Cognito as a user who has a tracked device. Signing in with a tracked device lets a user sign in without entering a new MFA code. Signing in with a tracked device requires that the client respond to the SRP protocol. The scenario associated with this example uses the warrant package to help with SRP calculations. For more information on SRP, see https://en.wikipedia.org/wiki/Secure_Remote_Password_protocol. :param user_name: The user that is associated with the device. :param password: The user's password. :param device_key: The key of a tracked device. :param device_group_key: The group key of a tracked device. :param device_password: The password that is associated with the device. :param aws_srp: A class that helps with SRP calculations. The scenario associated with this example uses the warrant package. :return: The result of the authentication. When successful, this contains an access token for the user. """ try: srp_helper = aws_srp.AWSSRP( username=user_name, password=device_password, pool_id="_", client_id=self.client_id, client_secret=None, client=self.cognito_idp_client, ) response_init = self.cognito_idp_client.initiate_auth( ClientId=self.client_id, AuthFlow="USER_PASSWORD_AUTH", AuthParameters={ "USERNAME": user_name, "PASSWORD": password, "DEVICE_KEY": device_key, }, ) if response_init["ChallengeName"] != "DEVICE_SRP_AUTH": raise RuntimeError( f"Expected DEVICE_SRP_AUTH challenge but got {response_init['ChallengeName']}." ) auth_params = srp_helper.get_auth_params() auth_params["DEVICE_KEY"] = device_key response_auth = self.cognito_idp_client.respond_to_auth_challenge( ClientId=self.client_id, ChallengeName="DEVICE_SRP_AUTH", ChallengeResponses=auth_params, ) if response_auth["ChallengeName"] != "DEVICE_PASSWORD_VERIFIER": raise RuntimeError( f"Expected DEVICE_PASSWORD_VERIFIER challenge but got " f"{response_init['ChallengeName']}." ) challenge_params = response_auth["ChallengeParameters"] challenge_params["USER_ID_FOR_SRP"] = device_group_key + device_key cr = srp_helper.process_challenge(challenge_params, {"USERNAME": user_name}) cr["USERNAME"] = user_name cr["DEVICE_KEY"] = device_key response_verifier = self.cognito_idp_client.respond_to_auth_challenge( ClientId=self.client_id, ChallengeName="DEVICE_PASSWORD_VERIFIER", ChallengeResponses=cr, ) auth_tokens = response_verifier["AuthenticationResult"] except ClientError as err: logger.error( "Couldn't start client sign in for %s. Here's why: %s: %s", user_name, err.response["Error"]["Code"], err.response["Error"]["Message"], ) raise else: return auth_tokens-
Para ter detalhes da API, consulte RespondToAuthChallenge na Referência do AWS SDK para a API do Python (Boto3).
-