使用软件开发工具包向亚马逊 Cognito 用户验证 MFA 应用程序 Amazon - Amazon Cognito
Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅 中国的 Amazon Web Services 服务入门 (PDF)

本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。

使用软件开发工具包向亚马逊 Cognito 用户验证 MFA 应用程序 Amazon

以下代码示例演示了如何向 Amazon Cognito 用户验证 MFA 应用程序。

操作示例是大型程序的代码摘录,必须在上下文中运行。在以下代码示例中,您可以查看此操作的上下文:

.NET
Amazon SDK for .NET
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整示例,了解如何进行设置和运行。

/// <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; }
  • 有关 API 的详细信息,请参阅 Amazon SDK for .NET API 参考VerifySoftwareToken中的。

C++
适用于 C++ 的 SDK
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整示例,了解如何进行设置和运行。

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 的详细信息,请参阅 Amazon SDK for C++ API 参考VerifySoftwareToken中的。

Java
适用于 Java 2.x 的 SDK
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整示例,了解如何进行设置和运行。

// 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 的详细信息,请参阅 Amazon SDK for Java 2.x API 参考VerifySoftwareToken中的。

JavaScript
适用于 JavaScript (v3) 的软件开发工具包
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整示例,了解如何进行设置和运行。

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 的详细信息,请参阅 Amazon SDK for JavaScript API 参考VerifySoftwareToken中的。

Kotlin
适用于 Kotlin 的 SDK
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整示例,了解如何进行设置和运行。

// 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 的详细信息,请参阅适用VerifySoftwareToken于 K otlin 的Amazon SDK API 参考

Python
适用于 Python (Boto3) 的 SDK
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整示例,了解如何进行设置和运行。

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 的详细信息,请参阅适用VerifySoftwareTokenPython 的Amazon SDK (Boto3) API 参考

有关 S Amazon DK 开发者指南和代码示例的完整列表,请参阅将此服务与 Amazon SDK 结合使用。本主题还包括有关入门的信息以及有关先前的 SDK 版本的详细信息。