使用软件开发工具包回应 Amazon Cognito 身份验证挑战 Amazon - Amazon Cognito
Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅 中国的 Amazon Web Services 服务入门 (PDF)

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

使用软件开发工具包回应 Amazon Cognito 身份验证挑战 Amazon

以下代码示例演示了如何响应 Amazon Cognito 身份验证质询。

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

.NET
Amazon SDK for .NET
注意

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

/// <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
注意

还有更多相关信息 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::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
注意

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

// 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
适用于 JavaScript (v3) 的软件开发工具包
注意

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

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
注意

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

// 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 (Boto3) 的 SDK
注意

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

通过提供关联的 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

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