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

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

InitiateAuth配 AWS 開發套件或 CLI 使用

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

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

.NET
AWS SDK for .NET
注意

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

/// <summary> /// Initiate authorization. /// </summary> /// <param name="clientId">The client Id of the application.</param> /// <param name="userName">The name of the user who is authenticating.</param> /// <param name="password">The password for the user who is authenticating.</param> /// <returns>The response from the initiate auth request.</returns> public async Task<InitiateAuthResponse> InitiateAuthAsync(string clientId, string userName, string password) { var authParameters = new Dictionary<string, string>(); authParameters.Add("USERNAME", userName); authParameters.Add("PASSWORD", password); var authRequest = new InitiateAuthRequest { ClientId = clientId, AuthParameters = authParameters, AuthFlow = AuthFlowType.USER_PASSWORD_AUTH, }; var response = await _cognitoService.InitiateAuthAsync(authRequest); Console.WriteLine($"Result Challenge is : {response.ChallengeName}"); return response; }
  • 如需 API 詳細資訊,請參閱 AWS SDK for .NET API 參考InitiateAuth中的。

Go
SDK for Go V2
注意

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

type CognitoActions struct { CognitoClient *cognitoidentityprovider.Client } // SignIn signs in a user to Amazon Cognito using a username and password authentication flow. func (actor CognitoActions) SignIn(clientId string, userName string, password string) (*types.AuthenticationResultType, error) { var authResult *types.AuthenticationResultType output, err := actor.CognitoClient.InitiateAuth(context.TODO(), &cognitoidentityprovider.InitiateAuthInput{ AuthFlow: "USER_PASSWORD_AUTH", ClientId: aws.String(clientId), AuthParameters: map[string]string{"USERNAME": userName, "PASSWORD": password}, }) if err != nil { var resetRequired *types.PasswordResetRequiredException if errors.As(err, &resetRequired) { log.Println(*resetRequired.Message) } else { log.Printf("Couldn't sign in user %v. Here's why: %v\n", userName, err) } } else { authResult = output.AuthenticationResult } return authResult, err }
  • 如需 API 詳細資訊,請參閱 AWS SDK for Go API 參考InitiateAuth中的。

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

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

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

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

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

此範例示範如何使用追蹤的裝置開始進行身分驗證。若要完成登入,用戶端必須正確回應安全遠端密碼 (SRP) 挑戰。

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 sign_in_with_tracked_device( self, user_name, password, device_key, device_group_key, device_password, aws_srp, ): """ Signs in to Amazon Cognito as a user who has a tracked device. Signing in with a tracked device lets a user sign in without entering a new MFA code. Signing in with a tracked device requires that the client respond to the SRP protocol. The scenario associated with this example uses the warrant package to help with SRP calculations. For more information on SRP, see https://en.wikipedia.org/wiki/Secure_Remote_Password_protocol. :param user_name: The user that is associated with the device. :param password: The user's password. :param device_key: The key of a tracked device. :param device_group_key: The group key of a tracked device. :param device_password: The password that is associated with the device. :param aws_srp: A class that helps with SRP calculations. The scenario associated with this example uses the warrant package. :return: The result of the authentication. When successful, this contains an access token for the user. """ try: srp_helper = aws_srp.AWSSRP( username=user_name, password=device_password, pool_id="_", client_id=self.client_id, client_secret=None, client=self.cognito_idp_client, ) response_init = self.cognito_idp_client.initiate_auth( ClientId=self.client_id, AuthFlow="USER_PASSWORD_AUTH", AuthParameters={ "USERNAME": user_name, "PASSWORD": password, "DEVICE_KEY": device_key, }, ) if response_init["ChallengeName"] != "DEVICE_SRP_AUTH": raise RuntimeError( f"Expected DEVICE_SRP_AUTH challenge but got {response_init['ChallengeName']}." ) auth_params = srp_helper.get_auth_params() auth_params["DEVICE_KEY"] = device_key response_auth = self.cognito_idp_client.respond_to_auth_challenge( ClientId=self.client_id, ChallengeName="DEVICE_SRP_AUTH", ChallengeResponses=auth_params, ) if response_auth["ChallengeName"] != "DEVICE_PASSWORD_VERIFIER": raise RuntimeError( f"Expected DEVICE_PASSWORD_VERIFIER challenge but got " f"{response_init['ChallengeName']}." ) challenge_params = response_auth["ChallengeParameters"] challenge_params["USER_ID_FOR_SRP"] = device_group_key + device_key cr = srp_helper.process_challenge(challenge_params, {"USERNAME": user_name}) cr["USERNAME"] = user_name cr["DEVICE_KEY"] = device_key response_verifier = self.cognito_idp_client.respond_to_auth_challenge( ClientId=self.client_id, ChallengeName="DEVICE_PASSWORD_VERIFIER", ChallengeResponses=cr, ) auth_tokens = response_verifier["AuthenticationResult"] except ClientError as err: logger.error( "Couldn't start client sign in for %s. Here's why: %s: %s", user_name, err.response["Error"]["Code"], err.response["Error"]["Message"], ) raise else: return auth_tokens
  • 如需 API 的詳細資訊,請參閱AWS 開發套件InitiateAuth中的 Python (博托 3) API 參考。

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