an AWS SDKAdminRespondToAuthChallenge와 함께 사용 - AWS SDK 코드 예제

AWS Doc SDK ExamplesWord AWS SDK 리포지토리에는 더 많은 GitHub 예제가 있습니다.

기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.

an AWS SDKAdminRespondToAuthChallenge와 함께 사용

다음 코드 예제는 AdminRespondToAuthChallenge의 사용 방법을 보여 줍니다.

작업 예제는 대규모 프로그램에서 발췌한 코드이며 컨텍스트에 맞춰 실행해야 합니다. 다음 코드 예제에서는 컨텍스트 내에서 이 작업을 확인할 수 있습니다.

.NET
AWS SDK for .NET
참고

더 많은 on GitHub가 있습니다. 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; }
C++
C++ SDK
참고

더 많은 on GitHub가 있습니다. 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; }
Java
Java 2.x용 SDK
참고

더 많은 on GitHub가 있습니다. 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()); }
JavaScript
SDK for JavaScript (v3)
참고

더 많은 on GitHub가 있습니다. 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); };
Kotlin
Kotlin용 SDK
참고

더 많은 on GitHub가 있습니다. 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 { region = "us-east-1" }.use { identityProviderClient -> val respondToAuthChallengeResult = identityProviderClient.adminRespondToAuthChallenge(adminRespondToAuthChallengeRequest) println("respondToAuthChallengeResult.getAuthenticationResult() ${respondToAuthChallengeResult.authenticationResult}") } }
Python
Python용 SDK(Boto3)
참고

더 많은 on GitHub가 있습니다. AWS 코드 예시 리포지토리에서 전체 예시를 찾고 설정 및 실행하는 방법을 배워보세요.

연결된 MFA 애플리케이션에서 생성된 코드를 제공하여 MFA 챌린지에 응답합니다.

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