C++SDK용 를 사용하는 Amazon Cognito Identity Provider 예제 - AWS SDK 코드 예제

AWS 문서 예제 리포지토리에서 더 많은 SDK GitHub AWS SDK 예제를 사용할 수 있습니다.

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

C++SDK용 를 사용하는 Amazon Cognito Identity Provider 예제

다음 코드 예제에서는 Amazon Cognito Identity Provider와 AWS SDK for C++ 함께 를 사용하여 작업을 수행하고 일반적인 시나리오를 구현하는 방법을 보여줍니다.

작업은 대규모 프로그램에서 발췌한 코드이며 컨텍스트에 맞춰 실행해야 합니다. 작업은 개별 서비스 함수를 직접적으로 호출하는 방법을 보여주며 관련 시나리오의 컨텍스트에 맞는 작업을 볼 수 있습니다.

시나리오는 동일한 서비스 내에서 또는 다른 AWS 서비스와 결합된 상태에서 여러 함수를 호출하여 특정 태스크를 수행하는 방법을 보여주는 코드 예제입니다.

각 예제에는 컨텍스트에서 코드를 설정하고 실행하는 방법에 대한 지침을 찾을 수 있는 전체 소스 코드에 대한 링크가 포함되어 있습니다.

시작하기

다음 코드 예제에서는 Amazon Cognito 사용을 시작하는 방법을 보여줍니다.

SDK C++용
참고

에 대한 자세한 내용은 를 참조하세요 GitHub. AWS 코드 예시 리포지토리에서 전체 예시를 찾고 설정 및 실행하는 방법을 배워보세요.

CMakeLists.txt CMake 파일의 코드입니다.

# Set the minimum required version of CMake for this project. cmake_minimum_required(VERSION 3.13) # Set the AWS service components used by this project. set(SERVICE_COMPONENTS cognito-idp) # Set this project's name. project("hello_cognito") # Set the C++ standard to use to build this target. # At least C++ 11 is required for the AWS SDK for C++. set(CMAKE_CXX_STANDARD 11) # Use the MSVC variable to determine if this is a Windows build. set(WINDOWS_BUILD ${MSVC}) if (WINDOWS_BUILD) # Set the location where CMake can find the installed libraries for the AWS SDK. string(REPLACE ";" "/aws-cpp-sdk-all;" SYSTEM_MODULE_PATH "${CMAKE_SYSTEM_PREFIX_PATH}/aws-cpp-sdk-all") list(APPEND CMAKE_PREFIX_PATH ${SYSTEM_MODULE_PATH}) endif () # Find the AWS SDK for C++ package. find_package(AWSSDK REQUIRED COMPONENTS ${SERVICE_COMPONENTS}) if (WINDOWS_BUILD AND AWSSDK_INSTALL_AS_SHARED_LIBS) # Copy relevant AWS SDK for C++ libraries into the current binary directory for running and debugging. # set(BIN_SUB_DIR "/Debug") # If you are building from the command line, you may need to uncomment this # and set the proper subdirectory to the executables' location. AWSSDK_CPY_DYN_LIBS(SERVICE_COMPONENTS "" ${CMAKE_CURRENT_BINARY_DIR}${BIN_SUB_DIR}) endif () add_executable(${PROJECT_NAME} hello_cognito.cpp) target_link_libraries(${PROJECT_NAME} ${AWSSDK_LINK_LIBRARIES})

hello_cognito.cpp 소스 파일의 코드입니다.

#include <aws/core/Aws.h> #include <aws/cognito-idp/CognitoIdentityProviderClient.h> #include <aws/cognito-idp/model/ListUserPoolsRequest.h> #include <iostream> /* * A "Hello Cognito" starter application which initializes an Amazon Cognito client and lists the Amazon Cognito * user pools. * * main function * * Usage: 'hello_cognito' * */ int main(int argc, char **argv) { Aws::SDKOptions options; // Optionally change the log level for debugging. // options.loggingOptions.logLevel = Utils::Logging::LogLevel::Debug; Aws::InitAPI(options); // Should only be called once. int result = 0; { Aws::Client::ClientConfiguration clientConfig; // Optional: Set to the AWS Region (overrides config file). // clientConfig.region = "us-east-1"; Aws::CognitoIdentityProvider::CognitoIdentityProviderClient cognitoClient(clientConfig); Aws::String nextToken; // Used for pagination. std::vector<Aws::String> userPools; do { Aws::CognitoIdentityProvider::Model::ListUserPoolsRequest listUserPoolsRequest; if (!nextToken.empty()) { listUserPoolsRequest.SetNextToken(nextToken); } Aws::CognitoIdentityProvider::Model::ListUserPoolsOutcome listUserPoolsOutcome = cognitoClient.ListUserPools(listUserPoolsRequest); if (listUserPoolsOutcome.IsSuccess()) { for (auto &userPool: listUserPoolsOutcome.GetResult().GetUserPools()) { userPools.push_back(userPool.GetName()); } nextToken = listUserPoolsOutcome.GetResult().GetNextToken(); } else { std::cerr << "ListUserPools error: " << listUserPoolsOutcome.GetError().GetMessage() << std::endl; result = 1; break; } } while (!nextToken.empty()); std::cout << userPools.size() << " user pools found." << std::endl; for (auto &userPool: userPools) { std::cout << " user pool: " << userPool << std::endl; } } Aws::ShutdownAPI(options); // Should only be called once. return result; }
  • 자세한 API 내용은 참조ListUserPools의 섹션을 참조하세요. AWS SDK for C++ API

작업

다음 코드 예시에서는 AdminGetUser을 사용하는 방법을 보여 줍니다.

SDK C++용
참고

에 대한 자세한 내용은 를 참조하세요 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::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; }
  • 자세한 API 내용은 참조AdminGetUser의 섹션을 참조하세요. AWS SDK for C++ API

다음 코드 예시에서는 AdminInitiateAuth을 사용하는 방법을 보여 줍니다.

SDK C++용
참고

에 대한 자세한 내용은 를 참조하세요 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::AdminInitiateAuthRequest request; request.SetClientId(clientID); request.SetUserPoolId(userPoolID); request.AddAuthParameters("USERNAME", userName); request.AddAuthParameters("PASSWORD", password); request.SetAuthFlow( Aws::CognitoIdentityProvider::Model::AuthFlowType::ADMIN_USER_PASSWORD_AUTH); Aws::CognitoIdentityProvider::Model::AdminInitiateAuthOutcome outcome = client.AdminInitiateAuth(request); if (outcome.IsSuccess()) { std::cout << "Call to AdminInitiateAuth was successful." << std::endl; sessionResult = outcome.GetResult().GetSession(); } else { std::cerr << "Error with CognitoIdentityProvider::AdminInitiateAuth. " << outcome.GetError().GetMessage() << std::endl; }
  • 자세한 API 내용은 참조AdminInitiateAuth의 섹션을 참조하세요. AWS SDK for C++ API

다음 코드 예시에서는 AdminRespondToAuthChallenge을 사용하는 방법을 보여 줍니다.

SDK C++용
참고

에 대한 자세한 내용은 를 참조하세요 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; }

다음 코드 예시에서는 AssociateSoftwareToken을 사용하는 방법을 보여 줍니다.

SDK C++용
참고

에 대한 자세한 내용은 를 참조하세요 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::AssociateSoftwareTokenRequest request; request.SetSession(session); Aws::CognitoIdentityProvider::Model::AssociateSoftwareTokenOutcome outcome = client.AssociateSoftwareToken(request); if (outcome.IsSuccess()) { std::cout << "Enter this setup key into an authenticator app, for example Google Authenticator." << std::endl; std::cout << "Setup key: " << outcome.GetResult().GetSecretCode() << std::endl; #ifdef USING_QR printAsterisksLine(); std::cout << "\nOr scan the QR code in the file '" << QR_CODE_PATH << "." << std::endl; saveQRCode(std::string("otpauth://totp/") + userName + "?secret=" + outcome.GetResult().GetSecretCode()); #endif // USING_QR session = outcome.GetResult().GetSession(); } else { std::cerr << "Error with CognitoIdentityProvider::AssociateSoftwareToken. " << outcome.GetError().GetMessage() << std::endl; return false; }

다음 코드 예시에서는 ConfirmSignUp을 사용하는 방법을 보여 줍니다.

SDK C++용
참고

에 대한 자세한 내용은 를 참조하세요 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::ConfirmSignUpRequest request; request.SetClientId(clientID); request.SetConfirmationCode(confirmationCode); request.SetUsername(userName); Aws::CognitoIdentityProvider::Model::ConfirmSignUpOutcome outcome = client.ConfirmSignUp(request); if (outcome.IsSuccess()) { std::cout << "ConfirmSignup was Successful." << std::endl; } else { std::cerr << "Error with CognitoIdentityProvider::ConfirmSignUp. " << outcome.GetError().GetMessage() << std::endl; return false; }
  • 자세한 API 내용은 참조ConfirmSignUp의 섹션을 참조하세요. AWS SDK for C++ API

다음 코드 예시에서는 DeleteUser을 사용하는 방법을 보여 줍니다.

SDK C++용
참고

에 대한 자세한 내용은 를 참조하세요 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::DeleteUserRequest request; request.SetAccessToken(accessToken); Aws::CognitoIdentityProvider::Model::DeleteUserOutcome outcome = client.DeleteUser(request); if (outcome.IsSuccess()) { std::cout << "The user " << userName << " was deleted." << std::endl; } else { std::cerr << "Error with CognitoIdentityProvider::DeleteUser. " << outcome.GetError().GetMessage() << std::endl; }
  • 자세한 API 내용은 참조DeleteUser의 섹션을 참조하세요. AWS SDK for C++ API

다음 코드 예시에서는 ResendConfirmationCode을 사용하는 방법을 보여 줍니다.

SDK C++용
참고

에 대한 자세한 내용은 를 참조하세요 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::ResendConfirmationCodeRequest request; request.SetUsername(userName); request.SetClientId(clientID); Aws::CognitoIdentityProvider::Model::ResendConfirmationCodeOutcome outcome = client.ResendConfirmationCode(request); if (outcome.IsSuccess()) { std::cout << "CognitoIdentityProvider::ResendConfirmationCode was successful." << std::endl; } else { std::cerr << "Error with CognitoIdentityProvider::ResendConfirmationCode. " << outcome.GetError().GetMessage() << std::endl; return false; }

다음 코드 예시에서는 SignUp을 사용하는 방법을 보여 줍니다.

SDK C++용
참고

에 대한 자세한 내용은 를 참조하세요 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::SignUpRequest request; request.AddUserAttributes( Aws::CognitoIdentityProvider::Model::AttributeType().WithName( "email").WithValue(email)); request.SetUsername(userName); request.SetPassword(password); request.SetClientId(clientID); Aws::CognitoIdentityProvider::Model::SignUpOutcome outcome = client.SignUp(request); if (outcome.IsSuccess()) { std::cout << "The signup request for " << userName << " was successful." << std::endl; } else if (outcome.GetError().GetErrorType() == Aws::CognitoIdentityProvider::CognitoIdentityProviderErrors::USERNAME_EXISTS) { std::cout << "The username already exists. Please enter a different username." << std::endl; userExists = true; } else { std::cerr << "Error with CognitoIdentityProvider::SignUpRequest. " << outcome.GetError().GetMessage() << std::endl; return false; }
  • 자세한 API 내용은 참조SignUp의 섹션을 참조하세요. AWS SDK for C++ API

다음 코드 예시에서는 VerifySoftwareToken을 사용하는 방법을 보여 줍니다.

SDK C++용
참고

에 대한 자세한 내용은 를 참조하세요 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::VerifySoftwareTokenRequest request; request.SetUserCode(userCode); request.SetSession(session); Aws::CognitoIdentityProvider::Model::VerifySoftwareTokenOutcome outcome = client.VerifySoftwareToken(request); if (outcome.IsSuccess()) { std::cout << "Verification of the code was successful." << std::endl; session = outcome.GetResult().GetSession(); } else { std::cerr << "Error with CognitoIdentityProvider::VerifySoftwareToken. " << outcome.GetError().GetMessage() << std::endl; return false; }
  • 자세한 API 내용은 참조VerifySoftwareToken의 섹션을 참조하세요. AWS SDK for C++ API

시나리오

다음 코드 예시는 다음과 같은 작업을 수행하는 방법을 보여줍니다.

  • 사용자 이름, 암호 및 이메일 주소로 사용자를 가입시키고 확인합니다.

  • MFA 애플리케이션을 사용자와 연결하여 다중 인증을 설정합니다.

  • 암호와 MFA 코드를 사용하여 로그인합니다.

SDK C++용
참고

에 대한 자세한 내용은 를 참조하세요 GitHub. AWS 코드 예시 리포지토리에서 전체 예시를 찾고 설정 및 실행하는 방법을 배워보세요.

Aws::Client::ClientConfiguration clientConfig; // Optional: Set to the AWS Region (overrides config file). // clientConfig.region = "us-east-1"; //! Scenario that adds a user to an Amazon Cognito user pool. /*! \sa gettingStartedWithUserPools() \param clientID: Client ID associated with an Amazon Cognito user pool. \param userPoolID: An Amazon Cognito user pool ID. \param clientConfig: Aws client configuration. \return bool: Successful completion. */ bool AwsDoc::Cognito::gettingStartedWithUserPools(const Aws::String &clientID, const Aws::String &userPoolID, const Aws::Client::ClientConfiguration &clientConfig) { printAsterisksLine(); std::cout << "Welcome to the Amazon Cognito example scenario." << std::endl; printAsterisksLine(); std::cout << "This scenario will add a user to an Amazon Cognito user pool." << std::endl; const Aws::String userName = askQuestion("Enter a new username: "); const Aws::String password = askQuestion("Enter a new password: "); const Aws::String email = askQuestion("Enter a valid email for the user: "); std::cout << "Signing up " << userName << std::endl; Aws::CognitoIdentityProvider::CognitoIdentityProviderClient client(clientConfig); bool userExists = false; do { // 1. Add a user with a username, password, and email address. Aws::CognitoIdentityProvider::Model::SignUpRequest request; request.AddUserAttributes( Aws::CognitoIdentityProvider::Model::AttributeType().WithName( "email").WithValue(email)); request.SetUsername(userName); request.SetPassword(password); request.SetClientId(clientID); Aws::CognitoIdentityProvider::Model::SignUpOutcome outcome = client.SignUp(request); if (outcome.IsSuccess()) { std::cout << "The signup request for " << userName << " was successful." << std::endl; } else if (outcome.GetError().GetErrorType() == Aws::CognitoIdentityProvider::CognitoIdentityProviderErrors::USERNAME_EXISTS) { std::cout << "The username already exists. Please enter a different username." << std::endl; userExists = true; } else { std::cerr << "Error with CognitoIdentityProvider::SignUpRequest. " << outcome.GetError().GetMessage() << std::endl; return false; } } while (userExists); printAsterisksLine(); std::cout << "Retrieving status of " << userName << " in the user pool." << std::endl; // 2. Confirm that the user was added to the user pool. if (!checkAdminUserStatus(userName, userPoolID, client)) { return false; } std::cout << "A confirmation code was sent to " << email << "." << std::endl; bool resend = askYesNoQuestion("Would you like to send a new code? (y/n) "); if (resend) { // Request a resend of the confirmation code to the email address. (ResendConfirmationCode) Aws::CognitoIdentityProvider::Model::ResendConfirmationCodeRequest request; request.SetUsername(userName); request.SetClientId(clientID); Aws::CognitoIdentityProvider::Model::ResendConfirmationCodeOutcome outcome = client.ResendConfirmationCode(request); if (outcome.IsSuccess()) { std::cout << "CognitoIdentityProvider::ResendConfirmationCode was successful." << std::endl; } else { std::cerr << "Error with CognitoIdentityProvider::ResendConfirmationCode. " << outcome.GetError().GetMessage() << std::endl; return false; } } printAsterisksLine(); { // 4. Send the confirmation code that's received in the email. (ConfirmSignUp) const Aws::String confirmationCode = askQuestion( "Enter the confirmation code that was emailed: "); Aws::CognitoIdentityProvider::Model::ConfirmSignUpRequest request; request.SetClientId(clientID); request.SetConfirmationCode(confirmationCode); request.SetUsername(userName); Aws::CognitoIdentityProvider::Model::ConfirmSignUpOutcome outcome = client.ConfirmSignUp(request); if (outcome.IsSuccess()) { std::cout << "ConfirmSignup was Successful." << std::endl; } else { std::cerr << "Error with CognitoIdentityProvider::ConfirmSignUp. " << outcome.GetError().GetMessage() << std::endl; return false; } } std::cout << "Rechecking the status of " << userName << " in the user pool." << std::endl; if (!checkAdminUserStatus(userName, userPoolID, client)) { return false; } printAsterisksLine(); std::cout << "Initiating authorization using the username and password." << std::endl; Aws::String session; // 5. Initiate authorization with username and password. (AdminInitiateAuth) if (!adminInitiateAuthorization(clientID, userPoolID, userName, password, session, client)) { return false; } printAsterisksLine(); std::cout << "Starting setup of time-based one-time password (TOTP) multi-factor authentication (MFA)." << std::endl; { // 6. Request a setup key for one-time password (TOTP) // multi-factor authentication (MFA). (AssociateSoftwareToken) Aws::CognitoIdentityProvider::Model::AssociateSoftwareTokenRequest request; request.SetSession(session); Aws::CognitoIdentityProvider::Model::AssociateSoftwareTokenOutcome outcome = client.AssociateSoftwareToken(request); if (outcome.IsSuccess()) { std::cout << "Enter this setup key into an authenticator app, for example Google Authenticator." << std::endl; std::cout << "Setup key: " << outcome.GetResult().GetSecretCode() << std::endl; #ifdef USING_QR printAsterisksLine(); std::cout << "\nOr scan the QR code in the file '" << QR_CODE_PATH << "." << std::endl; saveQRCode(std::string("otpauth://totp/") + userName + "?secret=" + outcome.GetResult().GetSecretCode()); #endif // USING_QR session = outcome.GetResult().GetSession(); } else { std::cerr << "Error with CognitoIdentityProvider::AssociateSoftwareToken. " << outcome.GetError().GetMessage() << std::endl; return false; } } askQuestion("Type enter to continue...", alwaysTrueTest); printAsterisksLine(); { Aws::String userCode = askQuestion( "Enter the 6 digit code displayed in the authenticator app: "); // 7. Send the MFA code copied from an authenticator app. (VerifySoftwareToken) Aws::CognitoIdentityProvider::Model::VerifySoftwareTokenRequest request; request.SetUserCode(userCode); request.SetSession(session); Aws::CognitoIdentityProvider::Model::VerifySoftwareTokenOutcome outcome = client.VerifySoftwareToken(request); if (outcome.IsSuccess()) { std::cout << "Verification of the code was successful." << std::endl; session = outcome.GetResult().GetSession(); } else { std::cerr << "Error with CognitoIdentityProvider::VerifySoftwareToken. " << outcome.GetError().GetMessage() << std::endl; return false; } } printAsterisksLine(); std::cout << "You have completed the MFA authentication setup." << std::endl; std::cout << "Now, sign in." << std::endl; // 8. Initiate authorization again with username and password. (AdminInitiateAuth) if (!adminInitiateAuthorization(clientID, userPoolID, userName, password, session, client)) { return false; } Aws::String accessToken; { Aws::String mfaCode = askQuestion( "Re-enter the 6 digit code displayed in the authenticator app: "); // 9. Send a new MFA code copied from an authenticator app. (AdminRespondToAuthChallenge) 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; } std::cout << "You have successfully added a user to Amazon Cognito." << std::endl; } if (askYesNoQuestion("Would you like to delete the user that you just added? (y/n) ")) { // 10. Delete the user that you just added. (DeleteUser) Aws::CognitoIdentityProvider::Model::DeleteUserRequest request; request.SetAccessToken(accessToken); Aws::CognitoIdentityProvider::Model::DeleteUserOutcome outcome = client.DeleteUser(request); if (outcome.IsSuccess()) { std::cout << "The user " << userName << " was deleted." << std::endl; } else { std::cerr << "Error with CognitoIdentityProvider::DeleteUser. " << outcome.GetError().GetMessage() << std::endl; } } return true; } //! Routine which checks the user status in an Amazon Cognito user pool. /*! \sa checkAdminUserStatus() \param userName: A username. \param userPoolID: An Amazon Cognito user pool ID. \return bool: Successful completion. */ bool AwsDoc::Cognito::checkAdminUserStatus(const Aws::String &userName, const Aws::String &userPoolID, const Aws::CognitoIdentityProvider::CognitoIdentityProviderClient &client) { 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; } return outcome.IsSuccess(); } //! Routine which starts authorization of an Amazon Cognito user. //! This routine requires administrator credentials. /*! \sa adminInitiateAuthorization() \param clientID: Client ID of tracked device. \param userPoolID: An Amazon Cognito user pool ID. \param userName: A username. \param password: A password. \param sessionResult: String to receive a session token. \return bool: Successful completion. */ bool AwsDoc::Cognito::adminInitiateAuthorization(const Aws::String &clientID, const Aws::String &userPoolID, const Aws::String &userName, const Aws::String &password, Aws::String &sessionResult, const Aws::CognitoIdentityProvider::CognitoIdentityProviderClient &client) { Aws::CognitoIdentityProvider::Model::AdminInitiateAuthRequest request; request.SetClientId(clientID); request.SetUserPoolId(userPoolID); request.AddAuthParameters("USERNAME", userName); request.AddAuthParameters("PASSWORD", password); request.SetAuthFlow( Aws::CognitoIdentityProvider::Model::AuthFlowType::ADMIN_USER_PASSWORD_AUTH); Aws::CognitoIdentityProvider::Model::AdminInitiateAuthOutcome outcome = client.AdminInitiateAuth(request); if (outcome.IsSuccess()) { std::cout << "Call to AdminInitiateAuth was successful." << std::endl; sessionResult = outcome.GetResult().GetSession(); } else { std::cerr << "Error with CognitoIdentityProvider::AdminInitiateAuth. " << outcome.GetError().GetMessage() << std::endl; } return outcome.IsSuccess(); }