AWS SDK または CLI AdminInitiateAuthで を使用する - Amazon Cognito

翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。

AWS SDK または CLI AdminInitiateAuthで を使用する

以下のコード例は、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 の詳細については、「 API リファレンスAdminInitiateAuth」の「」を参照してください。 AWS SDK for .NET

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::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 の詳細については、「 API リファレンスAdminInitiateAuth」の「」を参照してください。 AWS SDK for C++

CLI
AWS CLI

認証を開始するには

この例では、ユーザー名 jane@example.com の ADMIN_NO_SRP_AUTH フローを使用して認証を開始します。

クライアントでは、サーバーベースの認証用のサインイン API (ADMIN_NO_SRP_AUTH) が有効になっている必要があります。

戻り値のセッション情報を使用して、 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\"}" } }
  • API の詳細については、「 コマンドリファレンスAdminInitiateAuth」の「」を参照してください。 AWS CLI

Java
SDK for Java 2.x
注記

については、「」を参照してください 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 の詳細については、「 API リファレンスAdminInitiateAuth」の「」を参照してください。 AWS SDK for Java 2.x

JavaScript
SDK for 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 の詳細については、「 API リファレンスAdminInitiateAuth」の「」を参照してください。 AWS SDK for JavaScript

Kotlin
SDK for Kotlin
注記

については、「」を参照してください 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 for Kotlin API リファレンスAdminInitiateAuthの「」を参照してください。

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 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 の詳細については、 AdminInitiateAuth AWS SDK for Python (Boto3) API リファレンスの「」を参照してください。

AWS SDK デベロッパーガイドとコード例の完全なリストについては、「」を参照してくださいAWS SDK でこのサービスを使用する。このトピックには、使用開始方法に関する情報と、以前の SDK バージョンの詳細も含まれています。