AWS SDK を使用して Amazon Cognito と管理者認証情報による認証を開始する - AWSSDK コードサンプル

まだまだありますAWSSDK のサンプルは以下にあります。AWSドキュメント SDK サンプル GitHubレポ。


AWS SDK を使用して Amazon Cognito と管理者認証情報による認証を開始する

次のコード例は、Amazon Cognito と管理者認証情報を使用して認証を開始する方法を示しています。



にはまだまだあります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 の詳細については、を参照してください。AdminInitiateAuthAWS SDK for .NETAPI リファレンス

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

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

のための SDKJavaScript(v3)

にはまだまだありますGitHub。用例一覧を検索し、AWS コード例リポジトリでの設定と実行の方法を確認してください。

const adminInitiateAuth = async ({ clientId, userPoolId, username, password, }) => { const client = createClientForDefaultRegion(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 の詳細については、を参照してください。AdminInitiateAuthAWS SDK for JavaScriptAPI リファレンス

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 の詳細については、を参照してください。AdminInitiateAuthAWSコトリン用 SDK API リファレンス

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 の詳細については、を参照してください。AdminInitiateAuthAWSPython (ボト3) 用 SDK API リファレンス