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

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

使用软件开发工具包获取 MFA 应用程序与 Amazon Cognito 用户关联的令牌 Amazon

以下代码示例演示了如何获取令牌,以将 MFA 应用程序与 Amazon Cognito 用户关联。

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

.NET
Amazon SDK for .NET
注意

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

/// <summary> /// Get an MFA token to authenticate the user with the authenticator. /// </summary> /// <param name="session">The session name.</param> /// <returns>The session name.</returns> public async Task<string> AssociateSoftwareTokenAsync(string session) { var softwareTokenRequest = new AssociateSoftwareTokenRequest { Session = session, }; var tokenResponse = await _cognitoService.AssociateSoftwareTokenAsync(softwareTokenRequest); var secretCode = tokenResponse.SecretCode; Console.WriteLine($"Use the following secret code to set up the authenticator: {secretCode}"); return tokenResponse.Session; }
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::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; }
Java
适用于 Java 2.x 的 SDK
注意

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

public static String getSecretForAppMFA(CognitoIdentityProviderClient identityProviderClient, String session) { AssociateSoftwareTokenRequest softwareTokenRequest = AssociateSoftwareTokenRequest.builder() .session(session) .build(); AssociateSoftwareTokenResponse tokenResponse = identityProviderClient .associateSoftwareToken(softwareTokenRequest); String secretCode = tokenResponse.secretCode(); System.out.println("Enter this token into Google Authenticator"); System.out.println(secretCode); return tokenResponse.session(); }
JavaScript
适用于 JavaScript (v3) 的软件开发工具包
注意

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

const associateSoftwareToken = (session) => { const client = new CognitoIdentityProviderClient({}); const command = new AssociateSoftwareTokenCommand({ Session: session, }); return client.send(command); };
Kotlin
适用于 Kotlin 的 SDK
注意

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

suspend fun getSecretForAppMFA(sessionVal: String?): String? { val softwareTokenRequest = AssociateSoftwareTokenRequest { session = sessionVal } CognitoIdentityProviderClient { region = "us-east-1" }.use { identityProviderClient -> val tokenResponse = identityProviderClient.associateSoftwareToken(softwareTokenRequest) val secretCode = tokenResponse.secretCode println("Enter this token into Google Authenticator") println(secretCode) return tokenResponse.session } }
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 get_mfa_secret(self, session): """ Gets a token that can be used to associate an MFA application with the user. :param session: Session information returned from a previous call to initiate authentication. :return: An MFA token that can be used to set up an MFA application. """ try: response = self.cognito_idp_client.associate_software_token(Session=session) except ClientError as err: logger.error( "Couldn't get MFA secret. Here's why: %s: %s", err.response["Error"]["Code"], err.response["Error"]["Message"], ) raise else: response.pop("ResponseMetadata", None) return response
  • 有关 API 的详细信息,请参阅适用AssociateSoftwareTokenPython 的Amazon SDK (Boto3) API 参考

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