使用 for Kotlin SDK 的 Amazon Cognito Identity Provider 範例 - AWS SDK 程式碼範例

文件範例儲存庫中有更多 AWS SDK可用的範例。 AWS SDK GitHub

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

使用 for Kotlin SDK 的 Amazon Cognito Identity Provider 範例

下列程式碼範例示範如何使用 for Kotlin 搭配 AWS SDKAmazon Cognito Identity Provider 來執行動作和實作常見案例。

Actions 是大型程式的程式碼摘錄,必須在內容中執行。雖然動作會示範如何呼叫個別服務函數,但您可以在其相關案例中查看內容中的動作。

案例是程式碼範例,示範如何透過呼叫服務內的多個函數或與其他 結合來完成特定任務 AWS 服務。

每個範例都包含完整原始程式碼的連結,您可以在其中找到如何在內容中設定和執行程式碼的指示。

動作

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

SDK 適用於 Kotlin
注意

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

suspend fun getAdminUser( userNameVal: String?, poolIdVal: String?, ) { val userRequest = AdminGetUserRequest { username = userNameVal userPoolId = poolIdVal } CognitoIdentityProviderClient { region = "us-east-1" }.use { identityProviderClient -> val response = identityProviderClient.adminGetUser(userRequest) println("User status ${response.userStatus}") } }
  • 如需API詳細資訊,請參閱AdminGetUser中的 AWS SDK for Kotlin API參考

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

SDK 適用於 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詳細資訊,請參閱AdminInitiateAuth中的 AWS SDK for Kotlin API參考

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

SDK 適用於 Kotlin
注意

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

// 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}") } }

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

SDK 適用於 Kotlin
注意

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

suspend fun getSecretForAppMFA(sessionVal: String?): String? { val softwareTokenRequest = AssociateSoftwareTokenRequest { session = sessionVal } CognitoIdentityProviderClient { region = "us-east-1" }.use { identityProviderClient -> val tokenResponse = identityProviderClient.associateSoftwareToken(softwareTokenRequest) val secretCode = tokenResponse.secretCode println("Enter this token into Google Authenticator") println(secretCode) return tokenResponse.session } }

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

SDK 適用於 Kotlin
注意

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

suspend fun confirmSignUp( clientIdVal: String?, codeVal: String?, userNameVal: String?, ) { val signUpRequest = ConfirmSignUpRequest { clientId = clientIdVal confirmationCode = codeVal username = userNameVal } CognitoIdentityProviderClient { region = "us-east-1" }.use { identityProviderClient -> identityProviderClient.confirmSignUp(signUpRequest) println("$userNameVal was confirmed") } }
  • 如需API詳細資訊,請參閱ConfirmSignUp中的 AWS SDK for Kotlin API參考

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

SDK 適用於 Kotlin
注意

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

suspend fun listAllUsers(userPoolId: String) { val request = ListUsersRequest { this.userPoolId = userPoolId } CognitoIdentityProviderClient { region = "us-east-1" }.use { cognitoClient -> val response = cognitoClient.listUsers(request) response.users?.forEach { user -> println("The user name is ${user.username}") } } }
  • 如需API詳細資訊,請參閱ListUsers中的 AWS SDK for Kotlin API參考

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

SDK 適用於 Kotlin
注意

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

suspend fun resendConfirmationCode( clientIdVal: String?, userNameVal: String?, ) { val codeRequest = ResendConfirmationCodeRequest { clientId = clientIdVal username = userNameVal } CognitoIdentityProviderClient { region = "us-east-1" }.use { identityProviderClient -> val response = identityProviderClient.resendConfirmationCode(codeRequest) println("Method of delivery is " + (response.codeDeliveryDetails?.deliveryMedium)) } }

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

SDK 適用於 Kotlin
注意

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

suspend fun signUp( clientIdVal: String?, userNameVal: String?, passwordVal: String?, emailVal: String?, ) { val userAttrs = AttributeType { name = "email" value = emailVal } val userAttrsList = mutableListOf<AttributeType>() userAttrsList.add(userAttrs) val signUpRequest = SignUpRequest { userAttributes = userAttrsList username = userNameVal clientId = clientIdVal password = passwordVal } CognitoIdentityProviderClient { region = "us-east-1" }.use { identityProviderClient -> identityProviderClient.signUp(signUpRequest) println("User has been signed up") } }
  • 如需API詳細資訊,請參閱SignUp中的 AWS SDK for Kotlin API參考

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

SDK 適用於 Kotlin
注意

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

// Verify the TOTP and register for MFA. suspend fun verifyTOTP( sessionVal: String?, codeVal: String?, ) { val tokenRequest = VerifySoftwareTokenRequest { userCode = codeVal session = sessionVal } CognitoIdentityProviderClient { region = "us-east-1" }.use { identityProviderClient -> val verifyResponse = identityProviderClient.verifySoftwareToken(tokenRequest) println("The status of the token is ${verifyResponse.status}") } }

案例

以下程式碼範例顯示做法:

  • 使用使用者名稱、密碼和電子郵件地址註冊並確認使用者。

  • 透過將MFA應用程式與使用者建立關聯來設定多重要素身分驗證。

  • 使用密碼和MFA程式碼登入。

SDK 適用於 Kotlin
注意

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

/** Before running this Kotlin code example, set up your development environment, including your credentials. For more information, see the following documentation: https://docs.aws.amazon.com/sdk-for-kotlin/latest/developer-guide/setup.html TIP: To set up the required user pool, run the AWS Cloud Development Kit (AWS CDK) script provided in this GitHub repo at resources/cdk/cognito_scenario_user_pool_with_mfa. This code example performs the following operations: 1. Invokes the signUp method to sign up a user. 2. Invokes the adminGetUser method to get the user's confirmation status. 3. Invokes the ResendConfirmationCode method if the user requested another code. 4. Invokes the confirmSignUp method. 5. Invokes the initiateAuth to sign in. This results in being prompted to set up TOTP (time-based one-time password). (The response is “ChallengeName”: “MFA_SETUP”). 6. Invokes the AssociateSoftwareToken method to generate a TOTP MFA private key. This can be used with Google Authenticator. 7. Invokes the VerifySoftwareToken method to verify the TOTP and register for MFA. 8. Invokes the AdminInitiateAuth to sign in again. This results in being prompted to submit a TOTP (Response: “ChallengeName”: “SOFTWARE_TOKEN_MFA”). 9. Invokes the AdminRespondToAuthChallenge to get back a token. */ suspend fun main(args: Array<String>) { val usage = """ Usage: <clientId> <poolId> Where: clientId - The app client Id value that you can get from the AWS CDK script. poolId - The pool Id that you can get from the AWS CDK script. """ if (args.size != 2) { println(usage) exitProcess(1) } val clientId = args[0] val poolId = args[1] // Use the console to get data from the user. println("*** Enter your use name") val inOb = Scanner(System.`in`) val userName = inOb.nextLine() println(userName) println("*** Enter your password") val password: String = inOb.nextLine() println("*** Enter your email") val email = inOb.nextLine() println("*** Signing up $userName") signUp(clientId, userName, password, email) println("*** Getting $userName in the user pool") getAdminUser(userName, poolId) println("*** Conformation code sent to $userName. Would you like to send a new code? (Yes/No)") val ans = inOb.nextLine() if (ans.compareTo("Yes") == 0) { println("*** Sending a new confirmation code") resendConfirmationCode(clientId, userName) } println("*** Enter the confirmation code that was emailed") val code = inOb.nextLine() confirmSignUp(clientId, code, userName) println("*** Rechecking the status of $userName in the user pool") getAdminUser(userName, poolId) val authResponse = checkAuthMethod(clientId, userName, password, poolId) val mySession = authResponse.session val newSession = getSecretForAppMFA(mySession) println("*** Enter the 6-digit code displayed in Google Authenticator") val myCode = inOb.nextLine() // Verify the TOTP and register for MFA. verifyTOTP(newSession, myCode) println("*** Re-enter a 6-digit code displayed in Google Authenticator") val mfaCode: String = inOb.nextLine() val authResponse1 = checkAuthMethod(clientId, userName, password, poolId) val session2 = authResponse1.session adminRespondToAuthChallenge(userName, clientId, mfaCode, session2) } 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 } } suspend fun resendConfirmationCode( clientIdVal: String?, userNameVal: String?, ) { val codeRequest = ResendConfirmationCodeRequest { clientId = clientIdVal username = userNameVal } CognitoIdentityProviderClient { region = "us-east-1" }.use { identityProviderClient -> val response = identityProviderClient.resendConfirmationCode(codeRequest) println("Method of delivery is " + (response.codeDeliveryDetails?.deliveryMedium)) } } // 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}") } } // Verify the TOTP and register for MFA. suspend fun verifyTOTP( sessionVal: String?, codeVal: String?, ) { val tokenRequest = VerifySoftwareTokenRequest { userCode = codeVal session = sessionVal } CognitoIdentityProviderClient { region = "us-east-1" }.use { identityProviderClient -> val verifyResponse = identityProviderClient.verifySoftwareToken(tokenRequest) println("The status of the token is ${verifyResponse.status}") } } suspend fun getSecretForAppMFA(sessionVal: String?): String? { val softwareTokenRequest = AssociateSoftwareTokenRequest { session = sessionVal } CognitoIdentityProviderClient { region = "us-east-1" }.use { identityProviderClient -> val tokenResponse = identityProviderClient.associateSoftwareToken(softwareTokenRequest) val secretCode = tokenResponse.secretCode println("Enter this token into Google Authenticator") println(secretCode) return tokenResponse.session } } suspend fun confirmSignUp( clientIdVal: String?, codeVal: String?, userNameVal: String?, ) { val signUpRequest = ConfirmSignUpRequest { clientId = clientIdVal confirmationCode = codeVal username = userNameVal } CognitoIdentityProviderClient { region = "us-east-1" }.use { identityProviderClient -> identityProviderClient.confirmSignUp(signUpRequest) println("$userNameVal was confirmed") } } suspend fun getAdminUser( userNameVal: String?, poolIdVal: String?, ) { val userRequest = AdminGetUserRequest { username = userNameVal userPoolId = poolIdVal } CognitoIdentityProviderClient { region = "us-east-1" }.use { identityProviderClient -> val response = identityProviderClient.adminGetUser(userRequest) println("User status ${response.userStatus}") } } suspend fun signUp( clientIdVal: String?, userNameVal: String?, passwordVal: String?, emailVal: String?, ) { val userAttrs = AttributeType { name = "email" value = emailVal } val userAttrsList = mutableListOf<AttributeType>() userAttrsList.add(userAttrs) val signUpRequest = SignUpRequest { userAttributes = userAttrsList username = userNameVal clientId = clientIdVal password = passwordVal } CognitoIdentityProviderClient { region = "us-east-1" }.use { identityProviderClient -> identityProviderClient.signUp(signUpRequest) println("User has been signed up") } }