AWS SDK를 사용하여 Amazon Cognito 사용자로 MFA 애플리케이션 확인 - AWS SDK 코드 예제

AWS문서 AWS SDK 예제 리포지토리에 더 많은 SDK 예제가 있습니다. GitHub

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

AWS SDK를 사용하여 Amazon Cognito 사용자로 MFA 애플리케이션 확인

다음 코드 예시는 MFA 애플리케이션을 Amazon Cognito 사용자로 확인하는 방법을 보여줍니다.

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

.NET
AWS SDK for .NET
참고

자세한 내용은 여기에서 확인할 수 있습니다. GitHub AWS 코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

/// <summary> /// Verify the TOTP and register for MFA. /// </summary> /// <param name="session">The name of the session.</param> /// <param name="code">The MFA code.</param> /// <returns>The status of the software token.</returns> public async Task<VerifySoftwareTokenResponseType> VerifySoftwareTokenAsync(string session, string code) { var tokenRequest = new VerifySoftwareTokenRequest { UserCode = code, Session = session, }; var verifyResponse = await _cognitoService.VerifySoftwareTokenAsync(tokenRequest); return verifyResponse.Status; }
C++
SDK for 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; }
Java
SDK for Java 2.x
참고

자세한 내용은 다음과 같습니다 GitHub. AWS 코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

// Verify the TOTP and register for MFA. public static void verifyTOTP(CognitoIdentityProviderClient identityProviderClient, String session, String code) { try { VerifySoftwareTokenRequest tokenRequest = VerifySoftwareTokenRequest.builder() .userCode(code) .session(session) .build(); VerifySoftwareTokenResponse verifyResponse = identityProviderClient.verifySoftwareToken(tokenRequest); System.out.println("The status of the token is " + verifyResponse.statusAsString()); } catch (CognitoIdentityProviderException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } }
  • API 세부 정보는 AWS SDK for Java 2.xAPI VerifySoftwareToken참조를 참조하십시오.

JavaScript
JavaScript (v3) 용 SDK
참고

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

const verifySoftwareToken = (totp) => { const client = new CognitoIdentityProviderClient({}); // The 'Session' is provided in the response to 'AssociateSoftwareToken'. const session = process.env.SESSION; if (!session) { throw new Error( "Missing a valid Session. Did you run 'admin-initiate-auth'?", ); } const command = new VerifySoftwareTokenCommand({ Session: session, UserCode: totp, }); return client.send(command); };
  • API 세부 정보는 AWS SDK for JavaScriptAPI VerifySoftwareToken참조를 참조하십시오.

Kotlin
SDK for Kotlin
참고

자세한 내용은 다음과 같습니다 GitHub. AWS 코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

// Verify the TOTP and register for MFA. suspend fun verifyTOTP(sessionVal: String?, codeVal: String?) { val tokenRequest = VerifySoftwareTokenRequest { userCode = codeVal session = sessionVal } CognitoIdentityProviderClient { region = "us-east-1" }.use { identityProviderClient -> val verifyResponse = identityProviderClient.verifySoftwareToken(tokenRequest) println("The status of the token is ${verifyResponse.status}") } }
  • API 세부 정보는 Kotlin API용 AWS SDK 레퍼런스를 참조하세요 VerifySoftwareToken.

Python
SDK for Python (Boto3)
참고

자세한 내용은 여기에서 확인할 수 있습니다. GitHub 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 verify_mfa(self, session, user_code): """ Verify a new MFA application that is associated with a user. :param session: Session information returned from a previous call to initiate authentication. :param user_code: A code generated by the associated MFA application. :return: Status that indicates whether the MFA application is verified. """ try: response = self.cognito_idp_client.verify_software_token( Session=session, UserCode=user_code ) except ClientError as err: logger.error( "Couldn't verify MFA. Here's why: %s: %s", err.response["Error"]["Code"], err.response["Error"]["Message"], ) raise else: response.pop("ResponseMetadata", None) return response
  • API에 대한 자세한 내용은 파이썬용 AWS SDK (Boto3) API 레퍼런스를 참조하십시오 VerifySoftwareToken.