搭AdminInitiateAuth配 AWS 開發套件或 CLI 使用 - Amazon Cognito

本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。

AdminInitiateAuth配 AWS 開發套件或 CLI 使用

下列程式碼範例會示範如何使用AdminInitiateAuth

動作範例是大型程式的程式碼摘錄,必須在內容中執行。您可以在下列程式碼範例的內容中看到此動作:

.NET
AWS SDK for .NET
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在AWS 設定和執行程式碼範例儲存庫

/// <summary> /// Initiate an admin auth request. /// </summary> /// <param name="clientId">The client ID to use.</param> /// <param name="userPoolId">The ID of the user pool.</param> /// <param name="userName">The username to authenticate.</param> /// <param name="password">The user's password.</param> /// <returns>The session to use in challenge-response.</returns> public async Task<string> AdminInitiateAuthAsync(string clientId, string userPoolId, string userName, string password) { var authParameters = new Dictionary<string, string>(); authParameters.Add("USERNAME", userName); authParameters.Add("PASSWORD", password); var request = new AdminInitiateAuthRequest { ClientId = clientId, UserPoolId = userPoolId, AuthParameters = authParameters, AuthFlow = AuthFlowType.ADMIN_USER_PASSWORD_AUTH, }; var response = await _cognitoService.AdminInitiateAuthAsync(request); return response.Session; }
  • 如需 API 詳細資訊,請參閱 AWS SDK for .NET API 參考AdminInitiateAuth中的。

C++
適用於 C++ 的 SDK
注意

還有更多關於 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 詳細資訊,請參閱 AWS SDK for C++ API 參考AdminInitiateAuth中的。

CLI
AWS CLI

若要啟動授權

此範例使用 ADMIN_NO_SRP_AUTH 流程對使用者名稱 jane@example.com 啟動授權

用戶端必須啟用以伺服器為基礎的驗證 (ADMIN_NO_SRP_AUTH) 的登入 API。

使用返回值中的會話信息來調用 admin-respond-to-auth-challenge。

命令:

aws cognito-idp admin-initiate-auth --user-pool-id us-west-2_aaaaaaaaa --client-id 3n4b5urk1ft4fl3mg5e62d9ado --auth-flow ADMIN_NO_SRP_AUTH --auth-parameters USERNAME=jane@example.com,PASSWORD=password

輸出:

{ "ChallengeName": "NEW_PASSWORD_REQUIRED", "Session": "SESSION", "ChallengeParameters": { "USER_ID_FOR_SRP": "84514837-dcbc-4af1-abff-f3c109334894", "requiredAttributes": "[]", "userAttributes": "{\"email_verified\":\"true\",\"phone_number_verified\":\"true\",\"phone_number\":\"+01xxx5550100\",\"email\":\"jane@example.com\"}" } }
Java
適用於 Java 2.x 的 SDK
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在AWS 設定和執行程式碼範例儲存庫

public static AdminInitiateAuthResponse initiateAuth(CognitoIdentityProviderClient identityProviderClient, String clientId, String userName, String password, String userPoolId) { try { Map<String, String> authParameters = new HashMap<>(); authParameters.put("USERNAME", userName); authParameters.put("PASSWORD", password); AdminInitiateAuthRequest authRequest = AdminInitiateAuthRequest.builder() .clientId(clientId) .userPoolId(userPoolId) .authParameters(authParameters) .authFlow(AuthFlowType.ADMIN_USER_PASSWORD_AUTH) .build(); AdminInitiateAuthResponse response = identityProviderClient.adminInitiateAuth(authRequest); System.out.println("Result Challenge is : " + response.challengeName()); return response; } catch (CognitoIdentityProviderException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } return null; }
  • 如需 API 詳細資訊,請參閱 AWS SDK for Java 2.x API 參考AdminInitiateAuth中的。

JavaScript
適用於 JavaScript (v3) 的開發套件
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在AWS 設定和執行程式碼範例儲存庫

const adminInitiateAuth = ({ clientId, userPoolId, username, password }) => { const client = new CognitoIdentityProviderClient({}); const command = new AdminInitiateAuthCommand({ ClientId: clientId, UserPoolId: userPoolId, AuthFlow: AuthFlowType.ADMIN_USER_PASSWORD_AUTH, AuthParameters: { USERNAME: username, PASSWORD: password }, }); return client.send(command); };
  • 如需 API 詳細資訊,請參閱 AWS SDK for JavaScript API 參考AdminInitiateAuth中的。

Kotlin
適用於 Kotlin 的 SDK
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在AWS 設定和執行程式碼範例儲存庫

suspend fun checkAuthMethod( clientIdVal: String, userNameVal: String, passwordVal: String, userPoolIdVal: String, ): AdminInitiateAuthResponse { val authParas = mutableMapOf<String, String>() authParas["USERNAME"] = userNameVal authParas["PASSWORD"] = passwordVal val authRequest = AdminInitiateAuthRequest { clientId = clientIdVal userPoolId = userPoolIdVal authParameters = authParas authFlow = AuthFlowType.AdminUserPasswordAuth } CognitoIdentityProviderClient { region = "us-east-1" }.use { identityProviderClient -> val response = identityProviderClient.adminInitiateAuth(authRequest) println("Result Challenge is ${response.challengeName}") return response } }
  • 有關 API 的詳細信息,請參閱 AWS SDK AdminInitiateAuth中的 Kotlin API 參考。

Python
適用於 Python (Boto3) 的 SDK
注意

還有更多關於 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 start_sign_in(self, user_name, password): """ Starts the sign-in process for a user by using administrator credentials. This method of signing in is appropriate for code running on a secure server. If the user pool is configured to require MFA and this is the first sign-in for the user, Amazon Cognito returns a challenge response to set up an MFA application. When this occurs, this function gets an MFA secret from Amazon Cognito and returns it to the caller. :param user_name: The name of the user to sign in. :param password: The user's password. :return: The result of the sign-in attempt. When sign-in is successful, this returns an access token that can be used to get AWS credentials. Otherwise, Amazon Cognito returns a challenge to set up an MFA application, or a challenge to enter an MFA code from a registered MFA application. """ try: kwargs = { "UserPoolId": self.user_pool_id, "ClientId": self.client_id, "AuthFlow": "ADMIN_USER_PASSWORD_AUTH", "AuthParameters": {"USERNAME": user_name, "PASSWORD": password}, } if self.client_secret is not None: kwargs["AuthParameters"]["SECRET_HASH"] = self._secret_hash(user_name) response = self.cognito_idp_client.admin_initiate_auth(**kwargs) challenge_name = response.get("ChallengeName", None) if challenge_name == "MFA_SETUP": if ( "SOFTWARE_TOKEN_MFA" in response["ChallengeParameters"]["MFAS_CAN_SETUP"] ): response.update(self.get_mfa_secret(response["Session"])) else: raise RuntimeError( "The user pool requires MFA setup, but the user pool is not " "configured for TOTP MFA. This example requires TOTP MFA." ) except ClientError as err: logger.error( "Couldn't start sign in for %s. Here's why: %s: %s", user_name, err.response["Error"]["Code"], err.response["Error"]["Message"], ) raise else: response.pop("ResponseMetadata", None) return response
  • 如需 API 的詳細資訊,請參閱AWS 開發套件AdminInitiateAuth中的 Python (博托 3) API 參考。

如需 AWS SDK 開發人員指南和程式碼範例的完整清單,請參閱搭配 AWS SDK 使用此服務。此主題也包含有關入門的資訊和舊版 SDK 的詳細資訊。