D’autres exemples de kits AWS SDK sont disponibles dans le référentiel GitHub AWS Doc SDK Examples
Utilisation de AdminRespondToAuthChallenge avec un kit AWS SDK ou une interface de ligne de commande
Les exemples de code suivants illustrent comment utiliser AdminRespondToAuthChallenge.
Les exemples d’actions sont des extraits de code de programmes de plus grande envergure et doivent être exécutés en contexte. Vous pouvez voir cette action en contexte dans l’exemple de code suivant :
- .NET
-
- SDK pour .NET
-
Note
Il y en a plus sur GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le référentiel d’exemples de code AWS
. /// <summary> /// Respond to an admin authentication challenge. /// </summary> /// <param name="userName">The name of the user.</param> /// <param name="clientId">The client ID.</param> /// <param name="mfaCode">The multi-factor authentication code.</param> /// <param name="session">The current application session.</param> /// <param name="clientId">The user pool ID.</param> /// <returns>The result of the authentication response.</returns> public async Task<AuthenticationResultType> AdminRespondToAuthChallengeAsync( string userName, string clientId, string mfaCode, string session, string userPoolId) { Console.WriteLine("SOFTWARE_TOKEN_MFA challenge is generated"); var challengeResponses = new Dictionary<string, string>(); challengeResponses.Add("USERNAME", userName); challengeResponses.Add("SOFTWARE_TOKEN_MFA_CODE", mfaCode); var respondToAuthChallengeRequest = new AdminRespondToAuthChallengeRequest { ChallengeName = ChallengeNameType.SOFTWARE_TOKEN_MFA, ClientId = clientId, ChallengeResponses = challengeResponses, Session = session, UserPoolId = userPoolId, }; var response = await _cognitoService.AdminRespondToAuthChallengeAsync(respondToAuthChallengeRequest); Console.WriteLine($"Response to Authentication {response.AuthenticationResult.TokenType}"); return response.AuthenticationResult; }-
Pour plus d’informations sur l’API, consultez AdminRespondToAuthChallenge dans la référence de l’API AWS SDK pour .NET.
-
- C++
-
- kit SDK pour C++
-
Note
Il y en a plus sur GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le référentiel d’exemples de code 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::AdminRespondToAuthChallengeRequest request; request.AddChallengeResponses("USERNAME", userName); request.AddChallengeResponses("SOFTWARE_TOKEN_MFA_CODE", mfaCode); request.SetChallengeName( Aws::CognitoIdentityProvider::Model::ChallengeNameType::SOFTWARE_TOKEN_MFA); request.SetClientId(clientID); request.SetUserPoolId(userPoolID); request.SetSession(session); Aws::CognitoIdentityProvider::Model::AdminRespondToAuthChallengeOutcome outcome = client.AdminRespondToAuthChallenge(request); if (outcome.IsSuccess()) { std::cout << "Here is the response to the challenge.\n" << outcome.GetResult().GetAuthenticationResult().Jsonize().View().WriteReadable() << std::endl; accessToken = outcome.GetResult().GetAuthenticationResult().GetAccessToken(); } else { std::cerr << "Error with CognitoIdentityProvider::AdminRespondToAuthChallenge. " << outcome.GetError().GetMessage() << std::endl; return false; }-
Pour plus d’informations sur l’API, consultez AdminRespondToAuthChallenge dans la référence de l’API AWS SDK pour C++.
-
- CLI
-
- AWS CLI
-
Pour répondre à une stimulation d’authentification
Il existe de nombreuses manières de répondre aux différentes stimulations d’authentification, en fonction de votre flux d’authentification, de la configuration du groupe d’utilisateurs et des paramètres utilisateur. L’exemple
admin-respond-to-auth-challengesuivant fournit un code d’authentification MFA par TOTP pour diego@example.com et termine la connexion. La mémorisation des appareils de ce groupe d’utilisateurs est activée, de sorte que le résultat de l’authentification renvoie également une nouvelle clé d’appareil.aws cognito-idp admin-respond-to-auth-challenge \ --user-pool-idus-west-2_EXAMPLE\ --client-id1example23456789\ --challenge-nameSOFTWARE_TOKEN_MFA\ --challenge-responsesUSERNAME=diego@example.com,SOFTWARE_TOKEN_MFA_CODE=000000\ --sessionAYABeExample...Sortie :
{ "ChallengeParameters": {}, "AuthenticationResult": { "AccessToken": "eyJra456defEXAMPLE", "ExpiresIn": 3600, "TokenType": "Bearer", "RefreshToken": "eyJra123abcEXAMPLE", "IdToken": "eyJra789ghiEXAMPLE", "NewDeviceMetadata": { "DeviceKey": "us-west-2_a1b2c3d4-5678-90ab-cdef-EXAMPLE11111", "DeviceGroupKey": "-ExAmPlE1" } } }Pour plus d’informations, consultez Flux d’authentification de l’administration dans le Guide du développeur Amazon Cognito.
-
Pour plus de détails sur l’API, consultez AdminRespondToAuthChallenge
dans la Référence des commandes de l’AWS CLI.
-
- Java
-
- SDK pour Java 2.x
-
Note
Il y en a plus sur GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le référentiel d’exemples de code AWS
. // Respond to an authentication challenge. public static void adminRespondToAuthChallenge(CognitoIdentityProviderClient identityProviderClient, String userName, String clientId, String mfaCode, String session) { System.out.println("SOFTWARE_TOKEN_MFA challenge is generated"); Map<String, String> challengeResponses = new HashMap<>(); challengeResponses.put("USERNAME", userName); challengeResponses.put("SOFTWARE_TOKEN_MFA_CODE", mfaCode); AdminRespondToAuthChallengeRequest respondToAuthChallengeRequest = AdminRespondToAuthChallengeRequest.builder() .challengeName(ChallengeNameType.SOFTWARE_TOKEN_MFA) .clientId(clientId) .challengeResponses(challengeResponses) .session(session) .build(); AdminRespondToAuthChallengeResponse respondToAuthChallengeResult = identityProviderClient .adminRespondToAuthChallenge(respondToAuthChallengeRequest); System.out.println("respondToAuthChallengeResult.getAuthenticationResult()" + respondToAuthChallengeResult.authenticationResult()); }-
Pour plus d’informations sur l’API, consultez AdminRespondToAuthChallenge dans la référence de l’API AWS SDK for Java 2.x.
-
- JavaScript
-
- Kit SDK pour JavaScript (v3)
-
Note
Il y en a plus sur GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le référentiel d’exemples de code AWS
. const adminRespondToAuthChallenge = ({ userPoolId, clientId, username, totp, session, }) => { const client = new CognitoIdentityProviderClient({}); const command = new AdminRespondToAuthChallengeCommand({ ChallengeName: ChallengeNameType.SOFTWARE_TOKEN_MFA, ChallengeResponses: { SOFTWARE_TOKEN_MFA_CODE: totp, USERNAME: username, }, ClientId: clientId, UserPoolId: userPoolId, Session: session, }); return client.send(command); };-
Pour plus d’informations sur l’API, consultez AdminRespondToAuthChallenge dans la référence de l’API AWS SDK pour JavaScript.
-
- Kotlin
-
- SDK pour Kotlin
-
Note
Il y en a plus sur GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le référentiel d’exemples de code AWS
. // Respond to an authentication challenge. suspend fun adminRespondToAuthChallenge( userName: String, clientIdVal: String?, mfaCode: String, sessionVal: String?, ) { println("SOFTWARE_TOKEN_MFA challenge is generated") val challengeResponsesOb = mutableMapOf<String, String>() challengeResponsesOb["USERNAME"] = userName challengeResponsesOb["SOFTWARE_TOKEN_MFA_CODE"] = mfaCode val adminRespondToAuthChallengeRequest = AdminRespondToAuthChallengeRequest { challengeName = ChallengeNameType.SoftwareTokenMfa clientId = clientIdVal challengeResponses = challengeResponsesOb session = sessionVal } CognitoIdentityProviderClient.fromEnvironment { region = "us-east-1" }.use { identityProviderClient -> val respondToAuthChallengeResult = identityProviderClient.adminRespondToAuthChallenge(adminRespondToAuthChallengeRequest) println("respondToAuthChallengeResult.getAuthenticationResult() ${respondToAuthChallengeResult.authenticationResult}") } }-
Pour plus d’informations sur l’API, consultez AdminRespondToAuthChallenge
dans la référence de l’API du kit AWS SDK pour Kotlin.
-
- Python
-
- Kit SDK pour Python (Boto3)
-
Note
Il y en a plus sur GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le référentiel d’exemples de code AWS
. Répondez à une stimulation MFA en fournissant un code généré par une application MFA associée.
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 respond_to_mfa_challenge(self, user_name, session, mfa_code): """ Responds to a challenge for an MFA code. This completes the second step of a two-factor sign-in. When sign-in is successful, it returns an access token that can be used to get AWS credentials from Amazon Cognito. :param user_name: The name of the user who is signing in. :param session: Session information returned from a previous call to initiate authentication. :param mfa_code: A code generated by the associated MFA application. :return: The result of the authentication. When successful, this contains an access token for the user. """ try: kwargs = { "UserPoolId": self.user_pool_id, "ClientId": self.client_id, "ChallengeName": "SOFTWARE_TOKEN_MFA", "Session": session, "ChallengeResponses": { "USERNAME": user_name, "SOFTWARE_TOKEN_MFA_CODE": mfa_code, }, } if self.client_secret is not None: kwargs["ChallengeResponses"]["SECRET_HASH"] = self._secret_hash( user_name ) response = self.cognito_idp_client.admin_respond_to_auth_challenge(**kwargs) auth_result = response["AuthenticationResult"] except ClientError as err: if err.response["Error"]["Code"] == "ExpiredCodeException": logger.warning( "Your MFA code has expired or has been used already. You might have " "to wait a few seconds until your app shows you a new code." ) else: logger.error( "Couldn't respond to mfa challenge for %s. Here's why: %s: %s", user_name, err.response["Error"]["Code"], err.response["Error"]["Message"], ) raise else: return auth_result-
Pour plus d’informations sur l’API, consultez AdminRespondToAuthChallenge dans la référence de l’API du kit AWS SDK pour Python (Boto3).
-
- Swift
-
- Kit SDK pour Swift
-
Note
Il y en a plus sur GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le référentiel d’exemples de code AWS
. import AWSClientRuntime import AWSCognitoIdentityProvider /// Respond to the authentication challenge received from Cognito after /// initiating an authentication session. This involves sending a current /// MFA code to the service. /// /// - Parameters: /// - cipClient: The `CognitoIdentityProviderClient` to use. /// - userName: The user's username. /// - clientId: The app client ID. /// - userPoolId: The user pool to sign into. /// - mfaCode: The 6-digit MFA code currently displayed by the user's /// authenticator. /// - session: The authentication session to continue processing. func adminRespondToAuthChallenge(cipClient: CognitoIdentityProviderClient, userName: String, clientId: String, userPoolId: String, mfaCode: String, session: String) async { print("=====> SOFTWARE_TOKEN_MFA challenge is generated...") var challengeResponsesOb: [String: String] = [:] challengeResponsesOb["USERNAME"] = userName challengeResponsesOb["SOFTWARE_TOKEN_MFA_CODE"] = mfaCode do { let output = try await cipClient.adminRespondToAuthChallenge( input: AdminRespondToAuthChallengeInput( challengeName: CognitoIdentityProviderClientTypes.ChallengeNameType.softwareTokenMfa, challengeResponses: challengeResponsesOb, clientId: clientId, session: session, userPoolId: userPoolId ) ) guard let authenticationResult = output.authenticationResult else { print("*** Unable to get authentication result.") return } print("=====> Authentication result (JWTs are redacted):") print(authenticationResult) } catch _ as SoftwareTokenMFANotFoundException { print("*** The specified user pool isn't configured for MFA.") return } catch _ as CodeMismatchException { print("*** The specified MFA code doesn't match the expected value.") return } catch _ as UserNotFoundException { print("*** The specified username, \(userName), doesn't exist.") return } catch _ as UserNotConfirmedException { print("*** The user \(userName) has not been confirmed.") return } catch let error as NotAuthorizedException { print("*** Unauthorized access. Reason: \(error.properties.message ?? "<unknown>")") } catch { print("*** Error responding to the MFA challenge.") return } }-
Pour plus de détails sur l’API, consultez AdminRespondToAuthChallenge
dans la Référence des API du kit AWS SDK pour Swift.
-